Home > OS >  Django: can I save a model from two modelforms?
Django: can I save a model from two modelforms?

Time:10-12

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.

CodePudding user response:

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()
  • Related