How to Validate Forms in Django

Forms are the entry gate of any application. So it’s really important to add some validation checks on the input fields. In this tutorial, We will see how to create forms in Django and how to validate forms in Django.

What is Form validation

Form validation is the main reason that any developer has to use Forms for. The basic security principle of any computer application is “do not trust the user input”.

That could be because the user passes in malicious data to compromise the application or the user has made a mistake in providing the needed data which in turn, unintentionally, breaks our application.

Whatever the case, every piece of user input has to be validated to keep our application secure and un-compromised.

Django validates a form when we run the is_valid() method and the validated data is placed in the cleaned_data attribute of the form. A coding example will clear all of our doubts caused by vague English statements.

At first, you

How to Create forms in Django

need to open your command prompt and type the following:

C:\Users\hp>django-admin startproject Registration
C:\Users\hp>cd Registation

Here, we have used the name of our project as Registration. You can choose whichever name you want.

Now, type:

C:\Users\hp\Registration>python runserver

You should get the above screen which signifies that your project is working perfectly.

Now, you need to create your application. Here, we are using our application name as Regapp, you can opt for any name.

C:\Users\hp\Registration>django-admin startapp Regapp

Now, open Pycharm(or any ide of your choice) and open “Registration”. Create a directory templates which will have a star director inside which we will have Base.html and Home.html. Similarly, create another static directory which will have style.css file.

Your tree should look like this:

Validate Forms in Django


Django settings for Registration project.

Generated by 'django-admin startproject' using Django 2.2.

For more information on this file, see

For the full list of settings and their values, see

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
# Quick-start development settings - unsuitable for production
# See

# SECURITY WARNING: keep the secret key used in production secret!
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True


# Application definition



ROOT_URLCONF = 'Registration.urls'

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [

WSGI_APPLICATION = 'Registration.wsgi.application'

# Database

    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

# Password validation

        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',

# Internationalization



USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)

STATIC_URL = '/static/'


"""Registration URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
from django.contrib import admin
from django.urls import path
from Regapp import views
urlpatterns = [

No changes required in Registration\Registration\ and  Registration\Registration\ Leave it as it is.

In Registration\Regapp\ write the following code:

from django.db import models

class Student(models.Model):
    No = models.IntegerField()
    Name = models.CharField(max_length=25)
    Age = models.IntegerField()
    Mob = models.IntegerField()
    Add = models.CharField(max_length=64)

After the changes in, we need to make changes in migrations and also add superuser.

To make changes in migrations, run the following code:

C:\Users\hp\Registration>python makemigrations

You will get the output like:

Migrations for 'Regapp':
    - Create model Student

now type:

C:\Users\hp\Registration>python migrate

You should get like this:

Run the server and check whether Student table is created or not. On running the server you should get like this:

Hence, now we need to create a superuser so that we can login in our application. To create a superuser:

C:\Users\hp\Registration>python createsuperuser

It will ask for the following details:

On running your server and entering your details, you should get like this:

Now we need to make change in Registration\Regapp\ accordingly:

from django.contrib import admin
from Regapp.models import Student

class StudentAdmin(admin.ModelAdmin):
    list_display = ['No','Name','Age','Mob','Add'],StudentAdmin)

Now, create a file in Regapp folder and write the following code:

from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = '__all__'

Adding validators to

We now need to add validators in Registration\Regapp\

from django.shortcuts import render

# Create your views here.
from django.shortcuts import render,redirect
from .models import Student
from .forms import StudentForm

def form_view(request):
    form = StudentForm()
    if request.method == 'POST':
        form = StudentForm(request.POST)
        if form.is_valid():
        return redirect('/')
    return render(request,'star/Home.html',{'form':form})

Forms in templates

A form is an element of an HTML page, and Django provides tools to render its fields correctly. It also gives default methods to format fields as a table, an unordered list or paragraphs.

So, let us make changes in Registration\templates\star\Base.html

<!DOCTYPE html>
{%load staticfiles%}
<html lang="en">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="{%static 'css/style.css'%}">
    <div class = "container" align="center">
        {%block child_block%}

And also make changes in Registration\templates\star\Home.html

<!DOCTYPE html>
{% extends 'star/Base.html'%}
{% load staticfiles %}
{%block child_block%}
<h1>Student Registration Form</h1>
<form method="post">
    {% csrf_token %}
    <input type = 'submit' class="btn btn-primary" value="submit">


Now, let us also add css file in Registration\static\css\style.css


You can add any background of your choice.

Now, let’s run the server and check for the output

Let’s add details to the Student Registration Form:

After entering the details when we login to the admin page and check the student tables, we should find the entered details:

Errors and rendering

The code which checks for the code validation is:

def form_view(request):
    form = StudentForm()
    if request.method == 'POST':
        form = StudentForm(request.POST)
        if form.is_valid():
        return redirect('/')
    return render(request,'star/Home.html',{'form':form})

To check for Form Validation, if we keep a field blank and then submit it, we get a pop-up message like this:


Now, you can generate all the forms with ease and take different types of input from the user. Forms are pretty powerful elements on a webpage. They also raise many ethical questions as they contain user-data. Therefore, always design forms in a secure manner which are following international rules.

Forms can do much more than this. There are different built-in forms for each task. Now, you can actually prepare a web-application on your own. Work on that, it will be fun.