1

Is there a way of combining multiple models in the same form class in the form.py file.

Right now I have three Models, and have to create three separate form classes in the form.py file using forms.Modelform for each form class.

I define the model for each form class in the Meta tag,

Something like:

class Form1(forms.ModelForm):

    # FORM META PARAMETERS
    class Meta:
        model = Model 1

class Form2(forms.ModelForm):

    # FORM META PARAMETERS
    class Meta:
        model = Model 2

class Form3(forms.ModelForm):

    # FORM META PARAMETERS
    class Meta:
        model = Model 3

Then I have to combine all three forms (a selection of fields from each Model), in the HTML template, so there is only one submit button.

Then I have to make sure I save each of the 3 forms, in the view.py file, so that things get saved from hitting one submit button

Question

Is there not a way of combining models into one form class to begin with in the form.py file?

It would make the coding upstream in the view, and html template a lot easier, more compact and less repititious! Only 1 form class name to handle!

Also all the error checks would be in one place, and I would be managing fewer form classes that will have different names elsewhere, in other *.py or *.html files, since fields from multiple models would be combined into just one form class, with one name.

Sachin
  • 117
  • 1
  • 10
  • I had a coworker as me this question this morning. At the moment, I don't think it's possible but someone with a broader knowledge base than my own might be able to show us how. \ – RiverRook Mar 01 '22 at 16:25
  • Does this answer your question? [Multiple Models in a single django ModelForm?](https://stackoverflow.com/questions/2770810/multiple-models-in-a-single-django-modelform) – CoatedMoose Feb 16 '23 at 06:08

1 Answers1

0

I had a coworker as me this question this morning. At the moment, I don't think it's possible but someone with a broader knowledge base than my own might be able to show us how. I think you're probably going to have to inherit from a default forms.Form model to do what you want to do.

RiverRook
  • 144
  • 10
  • Yes, I think its a common usecase to want to combine fields from multiple models into one HTML page, and an efficient way of doing this is having one well defined form class that handles this customised view. It can be done with separate forms linked to separate models, in a 1-to-1 way, but the coding upstream in the view.py, and html template becomes a bit nightmarish, reptitious, and prone to errors, given the number of form class names that have to be maintained. – Sachin Mar 01 '22 at 19:08