David Dahan
David Dahan

Reputation: 11162

Django: can I save a model from two modelforms?

I decided to organize my page using two separated forms to build a single model:

class MandateForm1(forms.ModelForm):
    class Meta:
        model = Mandate
        fields = ("field_a", "field_b"),

class MandateForm2(forms.ModelForm):
    class Meta:
        model = Mandate
        fields = ("field_c", "field_d"),

In my view, I would get something like:

form_1 = MandateForm1(request.POST)
form_2 = MandateForm2(request.POST)

This way, how can I create my model using Form save() method? As a current workaround, I'm using Mandate.objects.create(**form_1.cleaned_data, **form_2.cleaned_data). The drawback is I need to handle M2M manually with this method.

Thanks.

Upvotes: 1

Views: 25

Answers (1)

SamSparx
SamSparx

Reputation: 5257

The way you have phrased the question, this is all being submitted in the same POST from a single page. If that's true, you might be able to do something like:

if request.method == "POST" and form1.is_valid() and form2.is_valid():
    form1.instance.field_c = form2.instance.field_c
    form1.instance.field_d = form2.instance.field_d
    form1.save()

Upvotes: 1

Related Questions