Form validation using Django

djangoProgrammingServer Side Programming

In this article, we are going to learn how to validate a form in django. Django comes with build-in validators for forms. We can use them in the tutorial to validate forms.

You must familiar with the Django to follow along with this tutorial. If you are not familiar with Django, then this article is not for you.

Set up the basic Django project with the following commands.

mkdir form_validation

cd form_validation

python -m venv env (Activate environment based on your OS)

pip install django===3.0

django-admin startproject form_validation . (Don't forget dot(.) at the end)

python startapp validation

Now, create a filed called inside the validations app

We are going to validate a login form. See the following code of a Login model. Copy and paste it in the file of the validations folder.

from django.db import models

class User(models.Model):
# username field
username = models.CharField(max_length=30, blank=False, null=False)
# password field
password = models.CharField(max_length=8, blank=False, null=False)

Now, we have to migrate the models. To make migrations, run the following command.

python makemigrations

python migrate

Now, place the following code in file.


from django.forms import ModelForm
from django import forms

from validation.models import User

class UserForm(ModelForm):

   # meta data for displaying a form
   class Meta:
      # model
      model = User

      # displaying fields
      fields = '__all__'

   # method for cleaning the data
   def clean(self):
      super(UserForm, self).clean()

      # getting username and password from cleaned_data
      username = self.cleaned_data.get('username')
      password = self.cleaned_data.get('password')

      # validating the username and password
      if len(username) < 5:
         self._errors['username'] = self.error_class(['A minimum of 5 characters is required'])

      if len(password) < 8:
         self._errors['password'] = self.error_class(['Password length should not be less than 8 characters'])

      return self.cleaned_data

Create a templates folder and a template called home.html inside the app. And paste the following code inside the home template.


{% load crispy_forms_tags %}

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Form Validation</title>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<form action="" method="post">
{%csrf_token%} {{ form|crispy }}
<div class="form-group">
<button type="submit" class="btn btn-success">
Add User

Now, let's write some code in the file.

from django.shortcuts import render
from django.http import HttpResponse

from .forms import UserForm

# Create your views here.
def home_view(request):

   # cheking the request
   if request.method == 'POST':

      # passing the form data to LoginForm
      user_details = UserForm(request.POST)

      # validating the user_details with is_valid() method
      if user_details.is_valid():

         # writing data to the database

         # redirect to another page with success message
         return HttpResponse("Data submitted successfully")


         # redirect back to the user page with errors
         return render(request, 'validation/home.html', {'form':user_details})

         # in case of GET request
         form = UserForm(None)
         return render(request, 'validation/home.html', {'form':form})

Add the path of home.html template in the file of the project. See the below code. Replace the validation with your app name.

from django.contrib import admin
from django.urls import path

from validation.views import home_view

urlpatterns = [
   path('', home_view, name='home'),

After completing all the above steps, you can view the form in the browser.


If you have any doubts in the tutorial, mention them in the comment section.

Published on 13-Nov-2020 12:58:00