Table of contents
1.
Introduction
2.
Project Setup
3.
Making a Model
4.
Using Django ModelForm 
4.1.
The Django ModelForm Class
5.
Making the View
6.
Field types
7.
Frequently Asked Questions
8.
Key Takeaways
Last Updated: Mar 27, 2024

Django Model Form

Author Tanay kumar Deo
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Django is a prevalent choice if you have completed your front-end journey with HTMLCSS, and Javascript or want to dive straight into backend development. Django is popular because it is a highly efficient, high-level, python-based backend web framework. Django follows a Model, View, and Template (MVT) based architecture. Some of the heaviest and most popular websites today are based on Django. Django was designed to ease the process of development for developers. Hence, Django has a wide range of features that prevent code redundancy. One such feature is Django ModelForm. 

There is a high chance that if our web application has a database linked to a form, our Django model will resonate with the form template. What Django enables us to do is that it helps us map the model that we created with the form template. This helps make code less redundant, as we do not need to redefine the fields for the form.

In this blog, we will learn how to implement Django ModelForm with the help of an example project. 

Project Setup

Before learning about the Django  ModelForm class, let us set up our Django example project. Run the following commands on the terminal to make a test project.

django-admin startproject testProject
cd testProject
django-admin startapp testApp 

 

Doing this, you would have a new Django project called “testProject” containing an app called “testApp.” You should have the following directory structure:

If you face any difficulties in the setup or are new to Django, head over to this link to set up your project. 

Please refer to our Project Structure in Django blog to better understand Django Project Structure.

Making a Model

Django Model is an inbuilt feature in Django that is used to create tables in the database, and generally, a model in Django is a class used to store essential methods and fields.

Before we start using the Django ModelForm class, let us initialise a model in our application. For this example, we would be using a simple model with two text fields. This model would later be linked to a form using the Django ModelForm class Django provides us with. 

Head over to the models.py file in the testApp folder to make the model.

In the models.py file, add the following code:

from django.db import models

# declare a new model with a name "testModel"
class testModel(models.Model):
        # fields of the model
    title = models.CharField(max_length = 200)
    description = models.TextField()
    last_modified = models.DateTimeField(auto_now_add = True)


    def __str__(self):
        return self.title
You can also try this code with Online Python Compiler
Run Code

 

As we can see, in the above code, we have created a new model called “testModel which has two input fields called title and description.

After creating our model, we need to write it in our admin.py file to view it in the admin panel. To register this model, head to the admin.py file in the testApp directory and add the following code:

from django.contrib import admin
from .models import testModel

admin.site.register(testModel)
You can also try this code with Online Python Compiler
Run Code

 

Now we need to do the migrations. Migrations are Django’s way of propagating changes to our models (adding a field, deleting a model, etc.) into our database schema. For the same, run the following commands in the terminal.

python manage.py makemigrations
python manage.py migrate

 

After doing this, we can view the model in the admin panel after running the server.

To run the server, use the following command on the terminal.

python manage.py runserver  

 

Now, head over to http://localhost:8000/admin/testApp/testmodel/add/ to view the model.

The model should appear like this:

Admin panel

Using Django ModelForm 

Now that we have created a model let us directly form this model. Let us make a forms.py file in our app directory to do so. We will use the Django ModelForm class for the same. In this newly created file, add the following code:

from django import forms
from .models import testModel
  
// Create a ModelForm
class testForm(forms.ModelForm):


    class Meta:
        model = testModel
        fields = "__all__"

 

The Django ModelForm Class

The ModelForm class takes three arguments: 

  • Model’s name
  • Fields Argument - This argument takes names of all those fields from the model we need in our form. We can set the fields argument to “__all__” if we need all the arguments from our model to be taken as input from the user.
  • Exclude Argument - It is used to provide a list of field names that are to be excluded from validation and cleaning. We use the exclude parameter in the Meta class in our form to exclude specific fields from the ModelForm. 

ModelForm uses this argument to exclude fields that aren’t present on our form from being validated since we could not correct any errors raised.

Making the View

Let us make the corresponding view for the above form made using Django ModelForm.

In the views.py file in the app directory, add the following code:

from django.shortcuts import render

// Create your views here.
from .forms import testForm


def home_view(request):
    context ={}

    // Create object of form
    form = testForm(request.POST or None, request.FILES or None)
    
    // Check if form data is valid
    if form.is_valid():
        // Save the form data to model
        form.save()

    context['form']= form
    return render(request, "testApp/home.html", context)
You can also try this code with Online Python Compiler
Run Code

 

To complete our Model-View-Template structure, let us create a basic template for this form.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form method = "post" action="">
        {{form.as_ul}}
        <input type="submit"></input>
    </form>
</body>
</html>

 

Our form is complete! Head over to http://127.0.0.1:8000/ to view the form. Let us also enter some dummy details to see if they get added to our database or not.

Form

On clicking submit, this data should be added to our model. Let us check the admin panel for that.

Admin Panel
 

Output

As we can see, the form has successfully been integrated with the Model using the ModelForm class.

Field types

Each Django model field has a corresponding form field. For example, a DateField on a model is represented as a DateField on a form. Here is a list of form field conversions:

Model Field Form Field
AutoField Not represented in the form field
BigAutoField Not represented in the form field
BinaryField CharField, if editable=True on the model field, otherwise it is not represented in the form field.
BigIntegerField IntegerField with min value equals to -9223372036854775808 and max value equals to 9223372036854775807.
CharField CharField with max length equals to the model field’s max length and empty value set to None if null=True.
DateField DateField
DateTimeField DateTimeField
DecimalField DecimalField
DurationField DurationField
EmailField EmailField
FileField FileField
FilePathField FilePathField
FloatField FloatField
ForeignKey ModelChoiceField
ImageField ImageField
IntegerField IntegerField
IPAddressField IPAddressField
GenericIPAddressField GenericIPAddressField
JSONField JSONField
ManyToManyField ModelMultipleChoiceField
PositiveBigIntegerField IntegerField
PositiveIntegerField IntegerField
PositiveSmallIntegerField IntegerField
SlugField SlugField
SmallAutoField Not represented in the form field
SmallIntegerField IntegerField
TextField CharField having widget=forms.Textarea
TimeField TimeField
URLField URLField
UUIDField UUIDField

Frequently Asked Questions

  1. What is the need for the fields argument in the ModelForm class?
    Correctly using the fields argument is extremely important. Failure to do so can result in users accessing specific fields that were not supposed to be accessible.
     
  2. How can we add validations to forms made using ModelForm?
    We add validations to forms made using ModelForm class like standard forms in Django using the is_valid() and full_clean() methods.
     
  3. Difference between Django forms.Form and forms.ModelForm?
    Forms created from forms.Form are manually configured by us. We use these for forms that do not directly interact with models. For example, a contact form or a newsletter form.
    Whereas a form created from forms.ModelForm will be automatically created and then can later be tweaked by us.

Key Takeaways

This blog looked into the Django ModelForm helper class. We made a sample model and linked it to the ModelForm class. Now that you have experience with the Modelform class continue learning Django and backend web development using this link!

Don't stop here. Check out the blogs Best Django Books, Top 30 Basic Django Interview Questions: Part 1, and Top 30 Intermediate Django Interview Questions: Part 2.

We hope you found this blog helpful. Liked the blog? Then feel free to upvote and share it.

Live masterclass