[Fixed]-Django : Formset as form field


I’m not sure where the idea that you need to “embed a Formset as a field” comes from; this sounds like a case for the standard usage of formsets.

For example (making a whole host of assumptions about your models):

class OfficeForm(forms.Form):
  department = forms.ModelChoiceField(...
  room_number = forms.IntegerField(...

class StaffForm(forms.Form):
  name = forms.CharField(max_length=...
  email = forms.EmailField(...

from django.forms.formsets import formset_factory

StaffFormSet = formset_factory(StaffForm)

And then, for your view:

def add_office(request):
    if request.method == 'POST':
        form = OfficeForm(request.POST)
        formset = StaffFormSet(request.POST)

        if form.is_valid() && formset.is_valid():
            # process form data
            # redirect to success page
        form = OfficeForm()
        formset = StaffFormSet()

    # render the form template with `form` and `formset` in the context dict

Possible improvements:

  • Use the django-dynamic-formset jQuery plugin to get the probably-desired “add an arbitrary number of staff to an office” functionality without showing users a stack of blank forms every time.
  • Use model formsets instead (assuming the information you’re collecting is backed by Django models), so you don’t have to explicitly specify the field names or types.

Hope this helps.

Leave a comment