How to write Django Model Forms in just one line?

How to write Django Model Forms in just one line?

one liner model forms in Django

Gaurav Sharma's photo
Gaurav Sharma
·May 8, 2022·

1 min read

Subscribe to our newsletter and never miss any upcoming articles

Play this article

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.

 
Share this