zerg .
zerg .

Reputation: 169

Django saving multiple inline formsets

After switching to inline formset I ended up with:

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')

After trying to save all forms I managed to save only form1. How do I save all forms?

Upvotes: 1

Views: 771

Answers (1)

Wei Liu
Wei Liu

Reputation: 43

Django's formset is for multiple instances of the same form. You are trying to save multiple form classes, which is not what formset for.

One way is to build a form contains all the fields in the form your want to include, and when processing the form, create each individual form you want to process. The following is an simple illustration. You do something fancy too, by introspecting the models and create model forms automatically, but that's a long story...

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)

Upvotes: 1

Related Questions