Django保存多个内联表单集

时间:2013-10-18 08:55:39

标签: python django

切换到内联formset后,我最终得到:

def dns_view(request, domain):
    dnszone = get_object_or_404(DNSSQL, zone = domain)

    form1 = EditDNSZone(instance = dnszone)
    forms = EditDNSEntry(instance = dnszone, prefix = 'entries')
    formsmx = EditDNSEntryMX(instance = dnszone, prefix = 'mxentries')

尝试保存所有表单后,我设法只保存form1。 如何保存所有表格?

1 个答案:

答案 0 :(得分:1)

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)