How to write Django Model Forms in just one line?
one liner model forms in Django
Till this point of time, you have been creating form for your existing models in Django using ModelForm
class:
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.
Social Links
- LinkedIn: https://www.linkedin.com/in/mnamegaurav/
- YouTube: https://www.youtube.com/c/devjunction
- Website: https://gaurav.devjunction.in/
- GitHub: https://github.com/mnamegaurav
- Instagram: https://www.instagram.com/mnamegaurav/
- Twitter: https://twitter.com/mnamegaurav