Django 的表单集用于同一表单的多个实例。您正在尝试保存多个表单类,这不是 formset 的用途。
一种方法是构建一个表单,其中包含您想要包含的表单中的所有字段,并且在处理表单时,创建您想要处理的每个单独的表单。下面是一个简单的说明。您也可以通过内省模型并自动创建模型表单来做一些花哨的事情,但这是一个很长的故事......
class Form1(forms.Form):
a_field = forms.CharField()
class Form2(forms.Form):
b_field = forms.CharField()
class MainForm(forms.Form):
a_field = forms.CharField()
b_field = forms.CharField()
def __init__(self, **kwargs):
super(MainForm, self).__init__(**kwargs)
# This will work because the field name matches that of the small forms, data unknow to
# a form will just be ignored. If you have something more complex, you need to append
# prefix, and converting the field name here.
form1 = Form1(**kwargs)
form2 = Form2(**kwargs)