Reputation: 888
Would someone like to attempt a succinct explanation of what a form_factory, or a modelform_factory is in relation to a form / modelform?
Upvotes: 2
Views: 2376
Reputation: 308799
The modelform_factory
method is a method that returns a ModelForm
class. Here's an example of why it's useful.
If you have a simple view that uses a form for a single model, then there is no need for a factory, you can simply define the form:
class ProductForm(forms.ModelForm):
class Meta:
model = Product
def add_product_view(request):
form = ProductForm()
...
However, if your view needs to handle multiple models, then you might not want to have to define a form class for every model. The modelform_factory
lets you create the form class dynamically.
apps.get_model('newapp', 'mymodel')
def add_model_view(request, model_name):
Model = apps.get_model('myapp', model_name)
Form = modelform_factory(Model)
The Django admin uses modelform_factory
to generate model form classes dynamically. This means you don't need to define a model form every time you register a model in the Django admin.
Upvotes: 3