'Django - combining multiple models into the same form class
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RiverRook |
