Form validation using Django

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 manage.py startapp validation

Now, create a filed called forms.py 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 models.py 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 manage.py makemigrations

python manage.py migrate
Now, place the following code in forms.py 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">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Form Validation</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<h2>User</h2>
<form action="" method="post">
{%csrf_token%} {{ form|crispy }}
<div class="form-group">
<button type="submit" class="btn btn-success">
Add User
</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Now, let's write some code in the views.py 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
         user_details.save()

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

      else:

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

         # 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 urls.py 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('admin/', admin.site.urls),
   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.