Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to do Django form validation

Njoku Ifeanyi Gerald

In this shot, we’ll learn to do Django form validation. Django automatically has built-in methods that validate the data from the form.

Note: Django forms are similar to advanced HTMLHyperText Markup Language forms, except that they are more Python-oriented in nature.


First, install Django by using the following commands:

pip install pipenv
pipenv shell
pipenv install django

Next, create the Django project:

django-admin startproject DjangoForm ./
python startapp codebase
python migrate
python runserver


First, add the project name to the file, as shown below:



Note: codebase should be replaced by the name of your Django project.

Next, in the codebase application folder, go to the file and create the following model:

from django.db import models

# model named Post
class CommentModel(models.Model):
	name = models.CharField( max_length = 100, blank = False,null = False)
	comment = models.TextField(blank = False, null = False)
	time = models.DateTimeField(auto_now_add = True)

Once our model is created, register it in the file, as shown below:

from django.contrib import admin
from .models import CommentModel

Create the form

After completing the configuration, create a file for the form. In our case, the file is named

from logging import PlaceHolder
from django import forms
from .models import CommentModel

class CommentForm(forms.ModelForm):
    name = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'form-control',
        'placeholder': 'name'
    comment = forms.CharField(widget=forms.Textarea(attrs={
        'class': 'form-control',
        'placeholder': 'comment section'
    class Meta:
        model = CommentModel
        fields = ['name', 'comment']


    def clean(self):
        # data is feteched using the super function of django
        super(CommentForm, self).clean()

        name  = self.cleaned_data.get('name')
        comment = self.cleaned_data.get('comment')

        if len(name) < 3:
            self._errors['name'] = self.error_class([
                '3 characters and more is required for this field'
        if len(comment) < 4:
            self._errors['comment'] = self.error_class([
                'comments should be more than 4 characters'
        return self.cleaned_data

Now, create a view for our project with the form created. The corresponding file is shown below:

from django.shortcuts import render, redirect
from .models import CommentModel
from .forms import CommentForm

def home(request):
    form = CommentForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            return redirect ('home')
    context = {
        'form': form
    return render(request, 'app/home.html', context)
  • Next, in the codebase app folder, create a folder and name it templates.
  • Inside the templates folder, create another folder and name it app.
  • Inside the app folder, create the home.html file as shown below:
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="" rel="stylesheet" 
<body class="container mt-4">
    <form method="POST" action="">
        {% csrf_token %}
        <div class="form-group mb-3">
        <div class="form-group mb-3">
        <button class="btn btn-outline-success">Submit</button>


Set route URLs

Within the main folder, in the file, add a route to the URLs of the codebase app, as shown below:

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

urlpatterns = [
    # including the codebase file
    path('', include('codebase.urls'))

Finally, in the codebase folder, create a file called that contains the route to the home view:

from django.urls import path
#importing home function from
from .views import home

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

Access form

Once the entry process is complete, run the following commands:

python makemigrations

python migrate

In case you want to create a super-user, run the following command:

python createsuperuser

Once we’re ready to access the newly created form, run this command:

python runserver

The command above starts our server on the URL:, which can be accessed now.




Njoku Ifeanyi Gerald

View all Courses

Keep Exploring