Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 526
Mark Avatar asked May 30 '12 13:05

Mark


1 Answers

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.

like image 178
supervacuo Avatar answered Oct 18 '22 05:10

supervacuo