I’m using django’s form wizard for a survey, and I want to save the entire survey into a single model. I’ve split the model into multiple forms, in order to have a subset of the model in each FormWizard step.
The question is, how do I combine them back together at the end?
My models.py looks like this:
class BigSurvey(models.Model):
field1 = models.TextField()
field2 = models.TextField()
...
field40 = models.CharField(max_length=10)
and my forms.py is like this:
class FirstPageForm(ModelForm):
class Meta:
model = BigSurvey
fields = ('field1', 'field2')
class SecondPageForm(ModelForm):
class Meta:
model = BigSurvey
fields = ('field3', 'field4')
And so on, for four forms and 30 fields total. The fields of each subclassed model form, combined, are all of the fields in the BigSurvey model.
This allows me to spit the BigSurvey into four steps. Form wizard returns an object form_list, which is a list of each of the four forms (FirstPageForm, SecondPageForm, etc).
How can I combine these four forms into a single BigSurvey object to save?
UPDATE:
Solved by iterating over forms and fields and populating a new form with a dictionary of values. Populating by using setattr (as per Colleen’s answer below) results in an unbound form.
My working solution:
newvalues={}
for form in form_list:
for field in form.cleaned_data.keys():
newvalues[field]=form.cleaned_data[field]
newform = QuestForm(newvalues)
newform.save()
You could iterate over all of the fields in each form and assign BigSurvey fields to their values.