Saving multiple optional objects with a CreateView

Not easily - or I should say, not that appears to me to save you a whole lot of effort.

The Django-provided generic CBVs work best with single-model forms. They aren’t really designed to work with multiple models.

(Side note: The Django-provided generic CBVs are not the only possible CBVs. You could - if you had a desire to do so - create a set of CBVs that satisfied this use-case. I’ve never encountered a situation where I would have considered this to be desirable, but YMMV.)

That’s my recommendation.

Handling multiple models in a form isn’t fundamentally any different than handling 1, other than you’re doing things twice. (Note: You will want to use a prefix for each form instance.)

As a trivial example, taking as an excerpt from Working with forms | Django documentation | Django as a starting point, working with two forms is going to take the general shape of:

def get_name(request):
    if request.method == 'POST':
        form1 = NameForm(request.POST, prefix='name')
        form2 = PersonForm(request.POST, prefix='person')
        if form1.is_valid() and form2.is_valid():
            # ...
            return HttpResponseRedirect('/thanks/')
    else:
        form1 = NameForm(prefix='name')
        form2 = PersonForm(prefix='person')
    return render(request, 'name.html', {'form1': form1, 'form2': form2})

One aspect of this that I would suggest as a “mindset”, is that you pick one model as being the “base” model for the page - one that all other models relate to in some manner. That gives you your hook to find those related models to that “base” model.
(The specifics of that will depend upon how you want your page to function.)

1 Like