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
