Search code examples
djangodjango-modelsdjango-forms

What are modelform_factory() and modelformset_factory()? (Django)


What are Django modelform_factory() and modelformset_factory(), and how do they correlate to the Django models, forms and modelforms?


Solution

    • forms.Form can be used to explicitly define a form, specifying each of the form fields.
    • When working with a model, forms.ModelForm can be used, which is built on top of Form. ModelForm handles automatic declaration of form fields, some validations, and saving an instance.
    • modelform_factory() generates a ModelForm -- think of it as a kind of shortcut to define a default ModelForm for your model.
    • Similarly, modelformset_factory() generates a ModelFormSet, used with one-to-many relations.

    Examples where you can find automatically-generated forms or formsets include the Django admin and Generic Class Views.

    Official Django documentation: