liveBook · Manning

Modelform_factory

As explained in Django in Action

modelform_factory is a Django function that dynamically creates a ModelForm class from a model and configuration options.

modelform_factory is Django’s shortcut for dynamically creating a ModelForm class from a model and selected configuration. Give it a model and a fields list, and it produces a form ready to validate user input and populate model instances. section 7.2.3

Use the factory when a ModelForm mainly needs model association and field selection:

  • Pass the model class as the first argument. section 7.2.3
  • Pass fields explicitly, such as ["name", "description", "picture"]. Explicit selection prevents future model fields from appearing in a public form accidentally. section 7.4.3 section 7.2.3
  • Use other factory options for excluded fields, labels, widgets, help text, and error messages. section 7.2.3

A Venue form in two lines

from django import forms from bands.models import Venue VenueForm = forms.modelform_factory( Venue, fields=["name", "description", "picture"] ) The resulting VenueForm can be constructed empty for a GET request, with instance=venue for editing, or with request.POST and request.FILES for a submitted upload. Its save() method can then create or update the Venue. section 7.4.3

For uploaded images, pass request.FILES alongside request.POST. The form handles both inputs, while the template must use multipart/form-data. A self-service venue view can reuse the same generated form for adding and editing, then associate the saved venue with the user’s controlled venues. section 7.4.3

Listing 7.17 Create a form for a Venue using modelform_factory
# RiffMates/bands/forms.py
from django import forms
from bands.models import Venue

VenueForm = forms.modelform_factory(Venue,  #1
    fields=["name", "description", "picture"])  #2

Inspect the complete two-line Venue form definition, including the selected model fields. section 7.4.3

How Django in Action covers it

How deep it goes
Explains model and field arguments plus customization options, while stopping short of factory internals.
Examples
Demonstrates a Venue form and contrasts the factory with an equivalent SeekingAd ModelForm class.
What it assumes
Assumes a Django model and basic form usage while teaching the factory shortcut and explicit model-field selection.
What you can do after
Builds a dynamically configured ModelForm and applies it to create or edit model instances from submitted data.
How it connects
Connects ModelForm classes with Django models, form fields, file uploads, validation, and model instance saving.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.