Django model formsets

Just as standard Django forms can be grouped together as a set in what's called a Django formset, Django model forms can also be grouped into what's called a model formset. Similarly, just as Django model forms resemble standard Django forms, model formsets also have a lot of similarities with standard formsets.

Up next, I'll describe the particularities of model formsets building on the knowledge presented in the last part of Chapter 6 on standard formsets. So if you're unfamiliar with formset terms (e.g. factory and management form), go back an read this last section, as the following assumes you have prior knowledge on these basic formset concepts.

Model formset factory

The modelformset_factory() method is the centerpiece to working with model formsets. The modelformset_factory() method can accept up to nineteen arguments, nine of which are identical to standard formsets and the remaining ones specific to model formsets. The following snippet illustrates all the names and default values for each argument in the modelormset_factory() method, with bolded text representing model formset specific options.

modelformset_factory(model, queryset=model.objects.all(),
                    form=ModelForm,fields=None, exclude=None,
                  formset=BaseModelFormSet, extra=1, can_order=False, can_delete=False,
                  max_num=None, min_num=None, validate_max=False, validate_min=False, 
                  widgets=None, localized_fields=None,labels=None, 
                 help_texts=None, error_messages=None,
                  field_classes=None,formfield_callback=None)

As you can confirm in this snippet, the only required argument (i.e. that doesn't have a default value) for the modelformset_factory() method is model. The meaning for each argument is the following:

Tip See Chapter 6 for details on the additional modelformset_factory options, which were already described in the standard formsets section.

Given that model formset logic is a combination of the model form techniques described earlier and formset techniques described in Chapter 6, I won't readdress the same techniques once again. You can look over the book's source code for a working model formset example in the source code for Chapter 9 under the online app.