Till this point of time, you have been creating form for your existing models in Django using
from django import forms class MyModelForm(forms.ModelForm): # specify the name of model to use class Meta: model = MyModel fields = "__all__"
But there is a much simpler way to generate a form in Django with just one line of code.
You can create forms from a given model using the standalone function
modelform_factory(), instead of using a class definition.
This may be more convenient if you do not have many customizations to make:
from django.forms import modelform_factory MyModelForm = modelform_factory(MyModel, fields="__all__")
You are not limited to just that, you can define the fields to choose as well:
from django.forms import modelform_factory MyModelForm = modelform_factory(MyModel, fields=("email", "username"))
Follow Us for more daily crispy blogs like this.