Mark
Mark

Reputation: 195

Django : Formset as form field

one of the forms I need is a composite of simple fields (say "Department", "Building" and "RoomNumber"), and of dynamically generated pairs of fields (say "Name" and "Email"). Ideally, editing the contents of the simple fields and adding/removing dynamic field pairs would be done on a single form.

Code-wise, I'm wondering if trying to embed a Formset (of a form with the two dynamic fields) as a field in an ordinary form is a sensible approach or if there's another best practice to achieve what I'd like to accomplish.

Many thanks for any advice on these matters,

Upvotes: 19

Views: 11757

Answers (1)

supervacuo
supervacuo

Reputation: 9262

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
    else:
        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.

Upvotes: 23

Related Questions