我有3种不同的形式:
class Questions(forms.ModelForm):
class Meta:
model = Client
fields = ['life_areas', 'life_desires', 'life_ambitions',]
class BasicContact(forms.ModelForm):
class Meta:
model = Client
fields = ['status', 'first_name', 'email_address', 'country',]
class PhoneContact(forms.ModelForm):
class Meta:
model = Client
fields = ['phone_number', 'best_time', 'preferences',]
我创建了一个表单向导,使用这三种表单收集信息。
FORMS = [("questions", Questions),
("basiccontact", BasicContact),
("phonecontact", PhoneContact),]
class ClientFormWizard(SessionWizardView):
form_list = FORMS
def done(self, form_list, form_dict, **kwargs):
# get data from the forms
questions = form_dict['questions']
basiccontact = form_dict['basiccontact']
phonecontact = form_dict['phonecontact']
formdata = dict(questions.items() + basiccontact.items() + phonecontact.items())
clientform = ClientForm(formdata)
new_client = clientform.save()
# return redirect(...)
我基本上试图将三种表单中的信息连接到一个ClientForm中,然后保存它。但是,我不确定如何连接三种形式的信息。我尝试用字典方式做,但它没有用。完成这种连接的最佳方法是什么?
编辑:在阅读Form API文档后,我终于弄明白了。这就是我汇总3种形式的信息的方式:
formdata = dict()
for f in form_list:
formdata.update(f.cleaned_data)
form_list包含提交的所有表单的实例。我们只是提取这些信息并将其放入一个名为formdata的新词典中。在那之后,它可以工作。
答案 0 :(得分:1)
不使用some_form.items()
,而是使用some_form.cleaned_data
,它将返回经过验证的POST数据的字典。
所以,正如你所知,它会显示:
FORMS = [("questions", Questions),
("basiccontact", BasicContact),
("phonecontact", PhoneContact),]
class ClientFormWizard(SessionWizardView):
form_list = FORMS
def done(self, form_list, form_dict, **kwargs):
# get data from the forms
form_data = dict()
for form in form_list:
form_data.update(form.cleaned_data)
clientform = ClientForm(form_data)
new_client = clientform.save()
# return redirect(...)