Using Django ModelForm – A Quick Guide

by Applied Informatics

Django is a free and open source python based web-framework that allows us to develop interactive web applications with easy to use syntax. Django is used by some of the leading websites in the world such as Pinterest, Instagram, Mozilla, The Washington Times, and Bitbucket. The main focus for django apps is re-usability, in addition to various other components that are present in the core package such as caching, internationalization, middleware, serialization, to name a few. In order to summarize flexibilty and nature of apps building in django, let us take a look at ModelForm in django.

ModelForm might come in handy if you are developing a Django app and want to represent a database model as a form. In essence, a ModelForm is a helper class that allows you to create a Django Form from a pre-existing model. To further explain the concept of ModelForm let us a consider a django app say for example myapp that has all the pre-requisites of a Django project, such as creating a project and creating an app inside the project directory.

Now, in let us create a model ‘Comment’:

from django.db import models
class Comment(models.Model):

    title = models.CharField(max_length=100)
    text = models.CharField(max_length=255)
    notes = models.CharField(max_length=255)

    def __str__(self):   # __unicode__ on Python 2
        return self.title

Let us attach this model to a form by creating a ModelForm for it. So add a file ‘’ and add modelform in it.

from django.forms import ModelForm
from myapp.models import Comment

class MyCommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ['title', 'text', 'notes']

Once the ModelForm is set, we can process it by writing a simple view in file, which most Django developers are familiar with.

from django.core.shortcuts import render, redirect
from django import forms
from django.utils import timezone
from myapp.forms import MyCommentForm
def add_model(request):

    if request.method == "POST":
        form = MyCommentForm(request.POST)
        if form.is_valid():
            model_instance =
            model_instance.timestamp =
            return redirect('/')


        form = MyCommentForm()

        return render(request, "my_template.html", {'form': form})

We can render the view to a template. For this create a template namely ‘my_template.html’

<DOCTYPE html>

<form method="post" >
{% csrf_token %}

<button type="submit" class="btn btn-default"&gt;Submit</button>

The new add_model() view adds several key pieces of functionality for handling forms. First, we check HTTP request method, to determine if it was a HTTP GET or POST. We can then handle different requests methods appropriately – i.e. whether we want to show a form (if it is a GET), or process form data (if it is a POST) – all from the same URL. The add_model() view function can handle three different scenarios:

  1. Show a new, blank form for adding a category.
  2. Save form data provided by user to the associated model, and rendering app homepage.
  3. If there are errors, re-display the form with error messages.

Summarizing usage of ModelForms,

  • ModelForms render Model fields as HTML.
  • ModelForms save a lot of time and HTML Hassle.
  • ModelForms select validators based off Model field definitions.
  • ModelForms don’t have to display/change all available fields.
  • ModelForms save dictionaries to SQL tables.

One thought on “Using Django ModelForm – A Quick Guide”

Leave a Reply

Your email address will not be published. Required fields are marked *

Tools & Practices

Tools and Technologies we use at Applied

Contact us now

Popular Posts