Django: Formset as a form field

one of the forms I need is a combination of simple fields (for example, "Department", "Construction" and "RoomNumber") and dynamically generated pairs of fields (for example, "Name" and "Email"). Ideally, editing the contents of simple fields and adding / removing pairs of dynamic fields would be done in one form.

Coding, I'm wondering if trying to embed a Formset (forms with two dynamic fields) as a field in a regular form is a reasonable approach or if there is other best practice to achieve what I do.

Thanks so much for any advice on these issues,

+6
source share
1 answer

I'm not sure where the idea comes from, that you need to “embed the form as a field”; this sounds like a case for standard use of form sets .

For example (making a number 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 "add an arbitrary number of employees to the office" without showing users a stack of blank forms every time.
  • Use model model blanks (assuming that the information you collect supports Django models), so you don’t need to explicitly specify field names or types.

Hope this helps.

+8
source

Source: https://habr.com/ru/post/917010/


All Articles