Python Django form validation

In this Python Django Tutorial, we will learn about Python Django form validation. And we will also see different examples related to form validation in Django. These are the following topics that we are going to discuss in this tutorial:

  • Python Django form validation
  • Django form validation example
  • Django form validation cleaned_data
  • Django form validation max_length
  • Django form validation error message
  • Django form validation checkbox
  • Django form validation required
  • Django form validation clean
  • Django form validation password
  • Djnago form validation whitespace
  • Djnago form validation integer
  • Django form validation multiple fields
  • Django form validation unique
  • Django admin form validation error
  • Django formvalidation custom
  • Django form validation exclude fields
  • Django form validation regex
  • Django form validation alphanumeric
  • Django form validation without model

Python Django form validation

In this section, we’ll look at Django’s Form Validation which means verification of form data. This validation is important to process as it increases security and it protects our form from unethical data.

Django includes built-in mechanisms for validating input in forms. And using these techniques, this verification may be done automatically. And, only CSRF tokens can submit the Django forms.

For validating the forms, we need to create a form and then collect a variety of inputs from the users, based on their needs and then apply form validations accordingly.

Also, check: Python Django vs ReactJS

Djnago form validation example

In this section, we’ll see an example related to form validation. And, to perform form validation, we’ll use the is_valid() method.

The is_vaild() function is used when we need to validate complete form data. It is defined in Django’s form class. In this validation, Python-datatypes will be checked. This function will return boolean results, i.e. it returns True if data is valid and otherwise False.

Let’s see an example related to form validation using the is_valid() method:

Create Project And App: Firstly, we have to create a project and app. So, to create it use the below define code.

# Project
django-admin startproject project_name

# App
python manage.py startapp app_name

Here, I create a project with the name PythonGuides and an app with the name myApp.

Install App: After, creating the project and app successfully. you have to install an App. For this, you have to add our app in the settings.py file.

python django form validation
Install App

Project’s URL: In the urls.py file, you have to add a link to your new app that is created. Add the below code snippets to the urls.py file of PythonGuides.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('myApp.urls'))
]

App’s URL: In the urls.py file, you have to add the path of the function views. Add the below code snippets to the urls.py file of the myApp.

from django.urls import path,include
from . import views
urlpatterns = [
path('emp_form', views.emp_form, name='emp_form'),
]

Models: Now, we create models. Add the below code snippets to the models.py file of the myApp.

from django.db import models

class EmpDetails(models.Model):
    Name = models.CharField(max_length=150)
    Email = models.EmailField()
    Contact = models.CharField(max_length=15)
    class Meta:
        db_table = "Employee Details"
  • Here we create different attributes such as Name, Email, and, Contact with specific datatypes which represent columns in the database.
  • To change the default name of the table, we pass the new table in db_table in the class Meta.

Form: Now, we create a form. And the below code snippets to forms.py file of the myApp.

from django import forms  
from .models import EmpDetails
  
class EmpDetailsForm(forms.ModelForm):  
    class Meta:  
        model = EmpDetails 
        fields = "__all__"  

Views: In the views.py file, implement the form and verify whether the form request is POST or not. And add the below code snippets.

from django.shortcuts import redirect, render
from myApp.forms import EmpDetailsForm

def emp_form(request):  
    if request.method == "POST":  
        form = EmpDetailsForm(request.POST)  
        if form.is_valid():  
            try:  
                return redirect('/')  
            except:  
                pass  
    else:  
        form = EmpDetailsForm()  
    return render(request,'form.html',{'form':form})  
  • Here we use the is_valid() method in view functions as it returns values as True and False.

Template: Now, create a forms.html template that shows forms and errors.

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Index</title>  
</head>  
<body>  
<form method="POST" class="post-form" enctype="multipart/form-data">  
        {% csrf_token %}  
        {{ form.as_p }}  
        <button type="submit" class="save btn btn-default">Submit</button>  
</form>  
</body>  
</html>  

Run the Server: Start the server and access the form. Form validates each field and shows you an error if any validation fails.

form validation using python django
Form validation using python Django
form validation using django
Form validation using Django
form validation example using django
Form validation example using Django

Read: Python Django random number

Django form validation cleaned_data

In this section, we’ll see an example related to form validation. And, to perform form validation, we’ll use the cleaned_data attribute.

The cleaned_data is used to validate certain fields. Basically, any information entered into a form will be sent to the server as strings. It makes no difference which type of form field was utilized when the form was created. Everything would ultimately be converted to strings by the browser.

So, we can say that Django automatically changes data to the appropriate type when it cleans it. This cleansed and validated data is referred to as cleaned data in Django. And, the cleaned data dictionary provides access to cleaned data.

The syntax is as:

self.cleaned_data['field_name']

Let’s see an example related to form validation using the cleaned_data().

Follow the following steps from the above section.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL

After this, follow the following steps:

Form: Now, we create a form. And add the below code snippets to the forms.py file of the myApp.

from django import forms  
  
class EmpDetailsForm(forms.Form):
    Name=forms.CharField(max_length=100)
    Email=forms.EmailField(label='Email')
    Contact=forms.CharField()
  • Here, we create a form class with the name EmpDetailsForm.
  • Next, we define Name, Email, and Contact as a field of the form.

Views: Implement the form in the views.py file and check whether the form request is POST or not. Add, the code snippets to the views.py file.

from django.shortcuts import redirect, render
from .forms import EmpDetailsForm

def emp_form(request):
    if request.method == "POST":  
        form = EmpDetailsForm(request.POST)
        if form.is_valid():
            Name = form.cleaned_data['Name']
            Email = form.cleaned_data['Email']
            Contact = form.cleaned_data['Contact']
            print('Name:', Name)
            print('Email:', Email)
            print('Conatct:', Contact)

    else:
        form =EmpDetailsForm()
    return render(request,'form.html',{'form':form})  
  • Here we use the is_valid() method in view functions as it returns values as True and False.
  • We also use the cleaned_data attribute with Name, Email, and Contact fields.
  • Then, we print the dictionary value of cleaned_data in the terminal.

Template: Now, create a forms.html template that shows the form and the errors.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form method="POST">
        {% csrf_token%}
        {{form.as_p}}
        
        <input type="submit" value="Submit">
    </form>

</body>

</html>
  • Here, we use the csrf_token tag is used in form to avoid malicious attacks.
  • Then, we use form.as_p tag to render Django forms as a paragraph.

Run the Server: Start the server and access the form by defining the URL as http://127.0.0.1:8000/emp_form.

django-form-validation-cleaned_data
django-form-validation-cleaned_data
django form validation cleaned_data a
Terminal Output

Read: Python Django set timezone

Django form validation max_length

In this section, we’ll look at a form validation example. And, to perform form validation, we’ll use the max_length attribute.

The max_length is one of the most commonly used validation attributes. It checks that the data entered in the field does not exceed the set maximum length. You can simply, use this attribute by providing max_length to the datatype.

Let’s look at examples:

Follow the following steps from the Django form validation example section.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL
  • Views
  • Templates

Note: We are not using the Model Class in this example, as we are working directly with Form Class.

Example #1

Form: Now, we create a form with the max_length validate attribute. Add the below code snippets to the forms.py file of the myApp.

from django import forms  
  
class EmpDetailsForm(forms.Form):
    Name=forms.CharField(max_length=8)
  • Here, we create a form class with name EmpDetailsForm, and we also add a feild to it with name “Name”.
  • Next, we provide max_length attribute to the CharField and set its value to 8.

Run the Server: Start the server and access the form by defining the URL as http://127.0.0.1:8000/emp_form.

form validation max_length using django
form validation max_length using Django

From, here you can see that I am trying to enter the Name Robert Johnson, which has a character length of more than 8.

django form validation max_length
Django form validation max_length

Note that you are not able to add more than 8 characters. That’s why it ignores extra characters here. And, it also counts whitespace as a character.

Example #2

Form: Now we’ll make a form using the max_length validator. And, add the following code snippets to the myApp’s forms.py file.

from django import forms
from matplotlib import widgets  
  
class EmpDetailsForm(forms.Form):
    Name=forms.CharField()
    Comment =forms.CharField(max_length=125, widget=forms.Textarea)
  • Here, we craete a EmpDetailsForm form class with Name and Comment feild.
  • We also apply max_length validator to Comment feild and specify the character length to 125 only.

Now, run the server and see the response.

form validation max_length using python django
form validation max_length using Python Django

From here you see that we are only able to add comments with 120 characters only.

Read: Python Django format date

Django form validation error message

In this section, we’ll look at a form validation example by using the error_message attribute.

The error_message attribute permits you to add custom error messages to the fields. This feature allows you to override the predefined error message and define your own. And, the error message is sent in the form of a dictionary data type.

Now, lets’ see examples related to this attribute.

Follow the following steps from the Django form validation example section.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL
  • Templates

Example #1

Form: Now, we create a form with the error_message validate attribute. And, add the below code to the forms.py file of the myApp.

from django import forms
from matplotlib import widgets 
  
class EmpDetailsForm(forms.Form):
    Name=forms.CharField(error_messages = {'required':'Enter your Full Name'})
    Username=forms.CharField(min_length=5)
    Password=forms.CharField(widget=forms.PasswordInput, error_messages = {'required':'Not use name as password'})
  • Here, we create a form class(EmpDetailsForm) with form fields such as Name, Username, and, Password.
  • And, we also add custom error message in Name and Password field by using error_message attribute.

View: Implement the form and verify whether the form request is POST or not. And add the below code snippets in the views.py file.

from django.shortcuts import redirect, render
from .forms import EmpDetailsForm

def emp_form(request):
    error = {}
    if request.method == "POST":  
        form = EmpDetailsForm(request.POST)
        error['form'] = form
        if form.is_valid():
            name = form.cleaned_data.get("Name")
            print(name)
            username = form.cleaned_data.get("Username")
            print(username)
            password = form.cleaned_data.get("Password")
            print(password)

    return render(request,'form.html',error)
  • Here we create a empty dictionary name as error.
  • Then, we use the Http request method POST, to send HTML form data to the server.
  • We also use the is_valid() method in view functions as it returns values as True and False.
  • We also use the cleaned_data.get(‘field’) to return None as the key does not exist in the dictionary

Now, run the server bypassing the http://127.0.0.1:8000/emp_form URL in the browser.

django form validation error message
Error Message

Example #2

Form: We’ll make a form with the validate error_message attribute. Add the following code to myApp’s forms.py file.

from django import forms
from matplotlib import widgets 
  
class EmpDetailsForm(forms.Form):
    Name=forms.CharField(error_messages = {'required':'Enter your Full Name'})
    Email=forms.EmailField()
    RateUs=forms.IntegerField(max_value=1, error_messages = {'required':'Give Rating between 1 to 5'})
    
  • We add custom error message in Name and RateUs field by using error_message attribute.

View: Add the below code snippets in the views.py file to implement the form.

from django.shortcuts import redirect, render
from .forms import EmpDetailsForm

def emp_form(request):
    error = {} 
    form = EmpDetailsForm(request.POST)
    error['form'] = form
    if request.POST:
        if form.is_valid():
            try:  
                return redirect('/')  
            except:  
                pass
        

    return render(request,'form.html',error)
             

Now, run the server.

form validation error message using django
form validation error message using Django

Read: Python Change Django Version

Django form validation checkbox

In this section, we’ll look at a form validation checkbox example, and to display the error we use the error_message attribute.

A checkbox is a two-state button that can be checked or unchecked. The CheckboxInput widget is the default widget for checkbox input. In a Django form, a boolean field is a checkbox field that stores either a True or False value. By default, the empty value is False.

Now, lets’ see examples related to this attribute.

From the Django form validation example section follow the following steps.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL
  • Templates

Example #1

Form: Now, we create a form with the checkbox error_message attribute. Add the below code to the forms.py file of the myApp.

from django import forms

class EmpDetailsForm(forms.Form):
    Agree = forms.BooleanField(label='Agree', required = True,  disabled = False,
                                  widget=forms.widgets.CheckboxInput(attrs={'class': 'checkbox-inline'}),
                                  help_text = "I accept the terms in the License Agreement",
                                  error_messages ={'required':'Please check the box'})
  • Here, we take data in the boolean field in the django forms.
  • And we pass th following parameters to it:
    • label: To specify the Field Caption.
    • required: Each field takes a value as required by default, you must set required = false to make it optional.
    • widget: Widget Argument to specify which widget classes should be used for showing this field. Here, we use CheckboxInput class.
    • error_message: To specify the custom error.

View: And the below code in views.py file.

from django.shortcuts import redirect, render
from .forms import EmpDetailsForm

def emp_form(request):
    error = {} 
    form = EmpDetailsForm(request.POST)
    error['form'] = form
    if request.POST:
        if form.is_valid():
            try:  
                return redirect('/')  
            except:  
                pass
        

    return render(request,'form.html',error)
   

Now, start the server by typing http://127.0.0.1:8000/emp_form into your browser’s address bar.

django form validation checkbox
Django form validation checkbox

Read: Get URL parameters in Django

Django form validation required

In this section, we’ll look at a form validation example by using the required attribute.

The required attribute is used with the fields that are mandatory to be entered by the user. This attribute can be used with any sort of input, such as email, URLs, text, files, passwords, checkboxes, radio buttons, and so forth.

Using this method, you can make input fields compulsory. And, by default the value is False.

Let’s see an example related to form validation using the required attribute:

From the Django form validation example section follow the following steps.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL
  • View
  • Templates

Example #1

Form: Now, we create a form with the required attribute. Add the below code to the forms.py file of the myApp.

from django import forms

class EmpDetailsForm(forms.Form):
    FirstName = forms.CharField(required=True)
    LastName = forms.CharField(required=False)
    Email = forms.EmailField(required=True)
  • Here, we make FirstName, and Email as required fields.
  • And, the LastName is non required, we can leave it blank also. As it is not compulsory.

Now, run the server.

django form validation required
Django form validation required
form validation required using django
form validation required using Django

From here you see that Please fill in this field message only activate on Firstname and Email field.

Example #2

Form: Now, we create a form by using the required attribute. Add the below code to the forms.py file of the myApp.

from django import forms

class EmpDetailsForm(forms.Form):
    Name = forms.CharField(required=True)
    Rating = forms.IntegerField(required=True, min_value=1, max_value=10)
    Comment = forms.CharField(max_length=250, widget=forms.Textarea, required=False)
  • Here, we make Name and Rating as required fields.
  • We also set the rating range from 1 to 1 bypassing min_value and max_value parameters.
  • And, the Comment is non required, we can leave it blank also. As it is not compulsory.
form validation required using python django
form validation required using Python Django
python django form validation required
Python Django form validation required

Read: Python Django get admin password

Django form validation clean

In this section, we’ll learn Django form validation clean() method with examples.

The clean() method is used with the form field class. It returns the clean data and then inserts it into the clean _data dictionary of the form. This method is used when we want to add custom validations that are interdependent.

This function is responsible to runs the three functions in a predefined order which are to_python(), validate(), and run_validators(). And, it also generates errors related to the functions. If the generated error is the ValidationError, the function stops the validation and raised the error.

The syntax is as below:

Form.clean()

Let’s see an example related to the clean() method:

Create Project And App: Firstly, we have to create a project and app. So, to create it use the below define code.

# Project
django-admin startproject PythonGuides .

# App
python manage.py startapp home

Here, I create a project with the name PythonGuides and an app with the name home.

Install App: After, creating the project and app successfully, you have to install an App. For this, you have to add our app in the settings.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home',
]

Project’s URL: You have to add a link to your new app that is created. Add the below code snippets to the urls.py file of PythonGuides.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('home.urls'))
]

App’s URL: You have to add the path of the function views. Add the below code snippets to the urls.py file of the home.

from django.urls import path,include
from . import views
urlpatterns = [
path('DetailForm', views.DetailForm, name='DetailForm'),
]

Form: Now, we create a form. And add the below code snippets to the forms.py file of the home.

from django import forms
from matplotlib import widgets

class EmpRegistration(forms.Form):
    Name = forms.CharField()
    Join_Date= forms.DateField()
    Leave_Date=forms.DateField()

    def clean(self):
        cleaned_data = super().clean()
        jdate = self.cleaned_data['Join_Date']
        ldate = self.cleaned_data['Leave_Date']

        if jdate > ldate:
            raise forms.ValidationError('Leaving Date must be after Joining Date')
  • Here, we create a form class EmpRegistration.
  • Then, we define Name, Join_Date, and Leave_Date as a field of the form.
  • After this, we use the clean method to clean and validate interdependent fields.
  • And here we shows a validate error if joining date is greater than leaving date.

Views: Implement the form in the views.py file and check whether the form request is POST or not.

from django.shortcuts import redirect, render
from .forms import EmpRegistration

def DetailForm(request):
    if request.method == "POST":  
        form = EmpRegistration(request.POST)
        if form.is_valid():
            print('Name:', form.cleaned_data['Name'])
            print('Join Date:', form.cleaned_data['Join_Date'])            
            print('Left Date:', form.cleaned_data['Leave_Date']) 
            
    else:
        form =EmpRegistration()
    return render(request,'home.html',{'form':form}) 
  • Here we use the is_valid() method in view functions as it returns values as True and False.
  • We also use the cleaned_data attribute with Name, Join Date, and Leave Date fields and also print their values in the terminals.

Template: Now, create a home.html template that shows the form and the errors in the browser.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form method="POST">
        {% csrf_token%}
        {{form.as_p}}
        
        <input type="submit" value="Submit">
    </form>

</body>

</html>

Run the Server: Start the server and access the form by defining the URL as http://127.0.0.1:8000/DetailForm.

django form validation clean example
Django form validation clean example

You can see that if we pass Leaving Date less than Joining Date, then Validation Error generates.

python django validation clean example
Python Django validation clean example
form validation clean example using django
Terminal Output

You can see that if we pass Joining Date greater than Leaving Date, then the error does not appear and the values are displayed at the terminal also.

Read: Python Django group by

Django form validation compare

In this section, we’ll learn the form validation compare using an example in Django.

In Django form validation compare, we’ll learn any two fields of the form and generate according to the requirement. So, let’s see an example to clearly understand the topic.

From the Django form validation clean section follow the following steps.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL
  • Templates

Form: Now, we create a form. And add the below code snippets to the forms.py file of the home.

from django import forms

class EmpRegistration(forms.Form):
    First_Name = forms.CharField(label='First Name')
    Last_Name = forms.CharField(label='Last Name')
    Email = forms.EmailField(label='Email')

    def clean(self):
        cleaned_data = super().clean()
        fname = self.cleaned_data['First_Name']
        lname = self.cleaned_data['Last_Name']

        if fname == lname:
            raise forms.ValidationError('First Name and Last Name should not be same')
  • Here, we create a form class EmpRegistration.
  • Then, we define First_Name, Last_Name, and Email as a field of the form.
  • We also, use the clean method to clean and validate interdependent fields. Here we are comparing First_Name and Last_Name.

Views: Implement the form in the views.py file and check whether the form request is POST or not.

from django.shortcuts import redirect, render
from .forms import EmpRegistration

def DetailForm(request):
    if request.method == "POST":  
        form = EmpRegistration(request.POST)
        if form.is_valid():
            print('First Name:', form.cleaned_data['First_Name'])
            print('Last Name:', form.cleaned_data['Last_Name'])
            print('Email:', form.cleaned_data['Email'])
    else:
        form =EmpRegistration()
    return render(request,'home.html',{'form':form}) 

Run the Server: Start the server and access the form by defining the URL as http://127.0.0.1:8000/DetailForm.

django form validation compare
Django form validation compare

From the output, you see that when we pass First Name and Last Name same, it generates a Validation Error.

python django validation compare
Python Django validation compare
form validation compare using django
Terminal Output

You can see that if we pass different First Name and Last Name, then the error does not appear and the values are displayed at the terminal also.

Read: How to Create model in Django

Django form validation password

In this section, we’ll learn the Django validation password method with an example.

The validate password is Django’s built-in feature. It is used to validate the password input by the user. The goal of the password validator is to ensure that password must not be simple.

The Django built-in password validator has the following rules:

  • Similarity: Its check password must not be similar to username, first_name, last_name, and email.
  • Minimum length: It checks the minimum length of the password. By default, the minimum length is 8.
  • Common Password: Django has a list of 20.000 records of common passwords.
  • Numeric: Password must not be fully numeric.

Define these password validators in the settings.py file.

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {'min_length':6}
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

Here, I change the default minimum length of the password and set it to 6.

Now, let’s see an example using a built-in password validator.

From the Django form validation clean section follow the following steps.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL
  • Templates

Form: Now, we create a form.

from django import forms
from matplotlib import widgets
from django.contrib.auth import password_validation

class EmpRegistration(forms.Form):
    username = forms.CharField(label='Username')
    password = forms.CharField(label='Password',widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html)
    confirm_Password = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)


    def clean(self):
        cleaned_data = super().clean()
        password1= self.cleaned_data['password']
        cpassword= self.cleaned_data['confirm_Password']

        if password1 != cpassword:
            raise forms.ValidationError('Confirm Password is not same as Password')
        password_validation.validate_password(self.cleaned_data.get('password',None))
        return self.cleaned_data
  • Here, we firstly import password_validation to activate and use these validators.
  • Then, we use the clean() method of Django and also raise an error if the Password is not the same as Confirm Password.
  • Now, we use django.contrib.auth.password_validation.validate_password() method and create clean password.

Views: Implement the form in the views.py file.

from django.shortcuts import redirect, render
from .forms import EmpRegistration

def DetailForm(request):
    if request.method == "POST":  
        form = EmpRegistration(request.POST)
        if form.is_valid():
            print('Username:', form.cleaned_data['username'])            
            print('Password:', form.cleaned_data['password']) 
            print('Confirm Password:', form.cleaned_data['confirm_Password'])
            
    else:
        form =EmpRegistration()
    return render(request,'home.html',{'form':form}) 

Now, run the server.

django form validation password
Django form validation password

Here I pass 12345 as a password, and you see that it shows an error.

Read: Compare two integers in Python Django

Django form validation whitespace

In this section, we’ll learn form validation whitespace with the example in Django.

By default, the Django model does not accept whitespace as a valid value. To validate whitespace in Django forms, we’ll use the blank option within the Django model field to which we want to permit whitespace

By default, the value of blank is False. To get whitespace acceptance, we change its boolean value to True.

Now, let’s see an example that validates whitespace.

From the Django form validation clean section follow the following steps.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL
  • Templates

Model: Create a model in the model.py file.

from django.db import models

class EmpRegistration(models.Model):
    EmployeeName = models.CharField(max_length=200)
    DOB = models.DateField()
    Address= models.CharField(max_length=400, blank=True)
    Email= models.EmailField()
    class Meta:
        db_table = "Employee Registration"
  • Here, we create the model class EmpRegistration.
  • We also define different attributes such as EmployeeName, DOB, Address, and Email with specific datatypes which represent columns in the database.
  • Then, to change the default name of the table to Employee Regsitration, we pass the new table in db_table in the class Meta.

Form: Create a form in the forms.py file.

from django import forms
from .models import EmpRegistration

class EmpRegistrationForm(forms.ModelForm):
    class Meta:
        model = EmpRegistration 
        fields = "__all__"

View: Create the view of the form in the views.py file.

from django.shortcuts import redirect, render
from .forms import EmpRegistrationForm

def DetailForm(request):
    if request.method == "POST":  
        form = EmpRegistrationForm(request.POST)
        if form.is_valid():
            print('Employee Name:', form.cleaned_data['EmployeeName'])            
            print('DOB:', form.cleaned_data['DOB']) 
            print('Address:', form.cleaned_data['Address'])
            print('Email:', form.cleaned_data['Email'])
                        
    else:
        form =EmpRegistrationForm()
    return render(request,'home.html',{'form':form}) 

Run the Server:

django form validation whitespace
Django form validation whitespace
form validation whitespace using django
Terminal Output

As you can see from the output, Django forms now validate whitespace and accept address blank.

Read: Python Django length filter

Django form validation integer

In this section, we’ll learn to apply integer validation on Django’s form. And, to print an error, we use the built-in error_message attribute of Django.

Now, let’s see an example of a form validation integer.

From the Django form validation clean section follow the following steps.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL
  • Templates

Example #1

Form: Create a form in the form.py file.

from django import forms

class EmpRegistration(forms.Form):
    Name = forms.CharField() 
    Email = forms.EmailField()
    Country = forms.CharField()
    City = forms.CharField()
    Pin_Code = forms.IntegerField(label='Pin Code', error_messages ={'required':'Pin Code should be 6 digits only'})
  • Here, we create a form class EmpRegistration.
  • Then, we define Name, Email, Country, City, and Pin_Code as a field of the form.
  • Here, we apply validation on integer feild of form that its max value be 6. And, it also shows an error message that Pin code should be 6 digits only.

Views: Implement the form in the views.py file.

from django.shortcuts import redirect, render
from .forms import EmpRegistration

def DetailForm(request):
    error = {} 
    form = EmpRegistration(request.POST)
    error['form'] = form
    if request.POST:
        if form.is_valid():
            try:  
                return redirect('/')  
            except:  
                pass
        

    return render(request,'home.html',error)

Now, run the server by entering bypassing http://127.0.0.1:8000/DetailForm in the address bar of the browser.

django form validation integer
Django form validation integer

Example #2

Form: Add the following code in the forms.py file.

from django import forms

class EmpRegistration(forms.Form):
    Name = forms.CharField() 
    Age = forms.IntegerField(min_value=22, max_value=60)
  • Here, we apply validation on integer feild of form that Age should be between 22 to 60.

View: Add the following code in the views.py file.

from django.shortcuts import redirect, render
from .forms import EmpRegistration

def DetailForm(request):
    if request.method == "POST":  
        form = EmpRegistration(request.POST)  
        if form.is_valid():  
            try:  
                return redirect('/')  
            except:  
                pass  
    else:  
        form = EmpRegistration()  
    return render(request,'home.html',{'form':form})  

Run the Server:

form validation integer using django
Form validation integer using Django
python django form validation integer
Python Django form validation integer

Django form validation multiple fields

In this section, we will learn to apply validation on more than one field of Django form class.

Now, let’s see an example of a form validation multiple fields.

Create Project And App: Create a project and an app by following the below commands.

# Project
django-admin startproject PythonGuides .

# App
python manage.py startapp myBlog

Here we create a project PythonGuides and an app myBlog.

Install App: After, the successful creation of an app install it. Open the settings.py file and add your app name.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myBlog',
]

Project’s URL: In the project’s urls.py file add the following code.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('myBlog.urls'))
]
  • Here we add a link to our new app that is created.

App’s URL: In the app’s urls.py file add the following code.

from django.urls import path
from . import views
urlpatterns = [
path('blog', views.blog, name='blog'),
]
  • Here we add the path of the function view.

Form: Create a form in the forms.py file and add the following code.

from django import forms

class BlogForm(forms.Form):
    Name = forms.CharField(max_length=250)
    post_title = forms.CharField(label='Post Title')
    Email = forms.EmailField(required=False)
    Update = forms.BooleanField(required=False, help_text='We will update you an email every time new post add')

    def clean(self):
        cleaned_data = super().clean()
        email = self.cleaned_data['Email']
        update = self.cleaned_data['Update']

        if update and not email:
            raise forms.ValidationError('The email must be provided if you are updating to the post')
  • Here we create a form BlogForm with the from fields Name, post_title, Email, and Update.
  • Then we validate two fields that are update and email.

Views: Create the view in the views.py file.

from django.shortcuts import redirect, render
from .forms import BlogForm

def blog(request):
    if request.method == "POST":  
        form = BlogForm(request.POST)
        if form.is_valid():
            print('Name:', form.cleaned_data['Name'])
            print('Post Title:', form.cleaned_data['post_title'])
            print('Email:', form.cleaned_data['Email'])            
            print('Update:', form.cleaned_data['Update']) 
            
    else:
        form = BlogForm()
    return render(request,'form.html',{'form':form}) 
  • Here we use the is_valid() and cleaned_data attribute in the blog function.

Template: Now, create a forms.html template.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form method="POST">
        {% csrf_token%}
        {{form.as_p}}
        
        <input type="submit" value="Submit">
    </form>

</body>

</html>

Run the Server: Start the server and access the form by defining the URL as http://127.0.0.1:8000/blog.

django form validation multiple fields
Django form validation multiple fields

From here you see that if you click on the Update button without providing an email, the error will generate.

python django form validation multiple fields
Python Django form validation multiple fields
form validation multiple fields using django
Terminal Output

If we provide Name and Email only, it will print values on the terminal.

Read: How to setup Django project

Django form validation unique

In this section, we will learn form validation unique with the example.

The unique attribute is used to set the form field to be unique. If once the value is entered in the form field, the same value can not be entered again in the same field.

By default, the value of unique is False. To set a field unique, set the value of the unique parameter to True.

The syntax is as follow:

field_name = models.Field(unique=True)

Let’s see an example related to form validation unique:

From the Django form validation multiple fields section follow the following steps.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL
  • Templates

Example #1

Model: In the models.py file, create the model. Because the unique attribute is only used in the model class.

from django.db import models

class Blog(models.Model):
    title= models.CharField(max_length=300, unique=True)
    author= models.CharField(max_length=200)

    def __str__(self):
        return self.title
  • Here we, create a model class Blog.
  • Then, we define title and author as a field of the form.
  • With a title field, we also use a unique attribute to prevent the same value from being entered twice.

Form: Create form class in forms.py file. Add the following code to it.

from django.forms import ModelForm
from .models import Blog
  
class BlogForm(ModelForm):  
    class Meta:  
        model = Blog 
        fields = ['title', 'author']
  • We created the Blog model above.
  • Now we want to create a form (BlogForm) that allows users to enter data.
  • Because we’ve already defined the fields in your model, defining the field types in your form would be unnecessary in this scenario.

View:

from django.shortcuts import redirect, render
from myBlog.forms import BlogForm

def blog(request):
    form = BlogForm(request.POST or None)
    if form.is_valid():
        form.save()  
        form = BlogForm()
    return render(request,'form.html',{'form':form})
  • The type of the request is set in the “method” attribute of the request object passed as a parameter to your view, and all data passed via POST may be viewed via the request. The POST dictionary is a collection of words that are used to express.
  • The is_valid() method is then used to validate each field of the form, followed by the save() method, which produces and saves a database object from the data linked to the form.
  • If is_valid is True, we then redirect to an HTML page form.

Run the Server: Now, run the server bypassing http://127.0.0.1:8000/blog in the address bar of the browser.

django form validation unique
Django form validation unique

Here, pass Title as Django installation and Author as Marry Smith.

form validation unique django
form validation unique Django

When we pass Title again as Django installation and Author as Robert an error raise Blog with this Title already exists because we use a unique attribute with title field.

Example #2

Model: In the models.py file, create the model by adding the following code.

from django.db import models

class Blog(models.Model):
    author= models.CharField(max_length=200)
    email= models.EmailField(unique=True)

Form: Create form class in forms.py file. Add the following code to it.

from django.forms import ModelForm
from .models import Blog
  
class BlogForm(ModelForm):  
    class Meta:  
        model = Blog 
        fields = ['author', 'email']

View: Add the following code in the views.py file.

from django.shortcuts import redirect, render
from myBlog.forms import BlogForm

def blog(request):
    form = BlogForm(request.POST or None)
    if form.is_valid():
        form.save()  
        form = BlogForm()
    return render(request,'form.html',{'form':form})

Run the Server:

python django form validation unique
Python Django form validation unique

Here, pass Author as Marry Smith and Email as marry@gmail.com.

form validation unique django python
form validation unique Django Python

When we pass Author as Marry Johnson and Email again as marry@gmail.com it rais an error Blog with this Email already exists because we use a unique attribute with an email field.

Read: What is Python Django and used for

Django admin form validation error

In this section, we’ll see a form validation error on the admin side.

Let’s see examples:

Create Project And App: Create project and app by executing the below code in the terminal.

# Project
django-admin startproject Employee

# App
python manage.py startapp myApp
  • Here, we create a project Employee and an app myApp.

Install App: Now, install the above-created app in the settings.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myApp',
]

Project’s URL: In the project’s urls.py file, you have to add a link to your new app.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('myApp.urls'))
]

App’s URL: In the app’s urls.py file, you have to add the path of the function views. 

from django.urls import path
from . import views
urlpatterns = [
path('App', views.App, name='App'),
]

Models: In the models.py file add the following code to create the model.

from django.db import models

class Employee(models.Model):
    EmpId = models.IntegerField(unique=True)
    Name = models.CharField(max_length=200)
    Assignment_Assign = models.CharField(max_length=500)
    Start_Date = models.DateField()
    End_Date = models.DateField()

Forms: In the forms.py file add the following code to create the form.

from django import forms
from .models import Employee

class EmployeeForm(forms.ModelForm):
    class Meta:
        model = Employee
        fields = ['EmpId', 'Name', 'Assignment_Assign', 'Start_Date', 'End_Date']

View: In the views.py file add the following code to view.

from django.shortcuts import redirect, render
from myApp.forms import EmployeeForm

def App(request):
    if request.method == "POST":  
        form = EmployeeForm(request.POST)
        if form.is_valid():
            print('Employee Id:', form.cleaned_data['EmpId'])
            print('Employee Name:', form.cleaned_data['Name'])            
            print('Assignment Assign:', form.cleaned_data['Assignment_Assign']) 
            print('Start Date:', form.cleaned_data['Start_Date'])
            print('End Date:', form.cleaned_data['End_Date'])
            form.save()
                        
    else:
        form =EmployeeForm()
    
    return render(request,'form.html',{'form':form})

Templates: Now, create a forms.html template.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form method="POST">
        {% csrf_token%}
        {{form.as_p}}
        
        <input type="submit" value="Submit">
    </form>

</body>
</html>

Run the Server: Start the server bypassing the http://127.0.0.1:8000/App URL in the browser.

django admin form validation error
Django admin form validation error

From here you clearly see that when you enter 101 as EmpId an error generates.

python admin form validation error
Python admin form validation error

Here, you clearly see that when we enter 101 as EmpId the same error generates.

Read: Python Django vs Flask

Django form validation custom

In this section, we’ll learn custom form validation.

Let’s say you have some fields that need to be validated, but there isn’t a built-in validator in such cases we create custom validators.

Steps to create custom validation:

  • Simply declare a function with the value of the parameter. That is the name of the parameter.
  • Then, on value, apply your desired validations. When a value meets any of the conditions, a ValidationError is raised.
  • Just as we did with validators, add that function_name to the validators parameter of the chosen field.

Let’s see examples to create custom form validation:

Example #1

From the Django form validation multiple fields section follow the following steps.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL
  • Templates

Form: Create form class using forms.py file. And add the following code.

from django import forms

def start_with(value):
  if value[0]!='A':
    raise forms.ValidationError("Post Code should start with A")
  

class BlogForm(forms.Form):
    Name = forms.CharField(max_length=250)
    post_code = forms.CharField(label='Post Code', validators=[start_with])
  • Here, we create custom validation function name start_with.
  • The function raise an error if value not start A.
  • Then, we create form class BlogForm with fields Name and Post_Code.
  • We use the custom validation function with post_code.

View: Add the following code in the views.py file.

from django.shortcuts import redirect, render
from .forms import BlogForm

def blog(request):
    if request.method == "POST":  
        form = BlogForm(request.POST)
        if form.is_valid():
            print('Name:', form.cleaned_data['Name'])
            print('Post Title:', form.cleaned_data['post_code'])
            
    else:
        form = BlogForm()
    return render(request,'form.html',{'form':form}) 

Run the Server:

form validation custom using python django
form validation custom using Python Django

Here we pass Post Code start with P, which raises an error.

django form validation custom
Django form validation custom
form validation custom using django
form validation custom using Django

When we enter a postcode that begins with the letter A, it is printed on the terminal.

Example #2

Follow the following steps from the Django form validation example section.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL
  • Templates

Form: Now, we create a form with the custom validation.

from django import forms
from matplotlib import widgets 
from django.core import validators

def check_pass_size(value):
    if len(value) > 10:
        raise forms.ValidationError("The Password is too long. It's length must be less than 10") 

  
class EmpDetailsForm(forms.Form):
    Name=forms.CharField()
    Username=forms.CharField(min_length=5)
    Password=forms.CharField(widget=forms.PasswordInput, validators=[check_pass_size])
  • Here, we create a custom validation function with the name check_pass_size.
  • This function checks the length of the password and raises an error if the length of the password is greater than 10.
  • Then, we create an EmpDetailsForm class with fields Name, Username, and Password.
  • And, we use the custom validation function with the Password field.

View: Add the following code in the views.py file.

from django.shortcuts import redirect, render
from .forms import EmpDetailsForm

def emp_form(request):
    if request.method == "POST":  
        form = EmpDetailsForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data.get("Name")
            print(name)
            username = form.cleaned_data.get("Username")
            print(username)
            password = form.cleaned_data.get("Password")
            print(password)
    else:
        form = EmpDetailsForm()

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

Run the Server: Run the server bypassing the http://127.0.0.1:8000/emp_form to the address bar of the browser.

Python Django form validation custom
Python Django form validation custom

We enter the password Johnson#12345, but an error occurs since the password is more than 10 characters.

form validation custom using django
form validation custom using Django
form validation custom using python django
form validation custom using Python Django

We enter the password marry@98, it accepts the password and prints it on the terminal.

Read How to encrypt and decrypt password in Django

Django form validation exclude fields

In this section, we’ll learn to exclude fields from Django forms.

When we have Django models with more fields than we wish to show in the Django Form, we use the exclude attribute.

Let’s see an example related to form validation exclude fields:

From the Django admin form validation error section follow the following steps.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL
  • Templates

Models: Add the following code in the models.py file to create the model.

from django.db import models

class Employee(models.Model):
    Employee_Id = models.IntegerField()
    Name = models.CharField(max_length=200)
    Assignment_Assign = models.CharField(max_length=500)
    Start_Date = models.DateField()
    End_Date = models.DateField()

Here, we create a model class Employee with Employee_Id, Name, Assignment_Assign, Start_Date, and End_Date fields.

Forms: Add the following code in the forms.py file to create the form.

from django import forms
from .models import Employee

class EmployeeForm(forms.ModelForm):
    class Meta:
        model = Employee
        exclude = ('Start_Date', 'End_Date')

Here, we exclude the Start_Date and End_Date fields from the form.

Views: Add the following code in the views.py file to create a view.

from django.shortcuts import redirect, render
from myApp.forms import EmployeeForm

def App(request):
    if request.method == "POST":  
        form = EmployeeForm(request.POST)
    else:
        form =EmployeeForm()
    
    return render(request,'form.html',{'form':form})

Run the Server: Enter the http://127.0.0.1:8000/App URL in your browser address box.

Django form validation exclude fields
Django form validation exclude fields

From here, you clearly see that the excluded fields are not shown on the form.

Django form validation regex

In this section, we’ll learn for validation using regular expressions.

A RegEx, or Regular Expression, is a pattern formed by a sequence of characters. It can be used to check if a string contains the specified pattern.

Let’s see examples related to form validation regex:

Create Project And App: Firstly, we have to create a project and app. So, to create it use the below define code.

# Project
django-admin startproject Registration

# App
python manage.py startapp student

Here, I create a project with the name Registration and an app with the name student.

Install App: Add student app in your settings.py INSTALLED_APPS.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'student',
]

Project’s URL: Add a link of your new app that is created in the project’s urls.py file.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('student.urls'))
]

App’s URL: Add the path of the function views in the app’s urls.py file.

from django.urls import path,include
from . import views
urlpatterns = [
path('stud_form', views.stud_form, name='stud_form'),
]

Models: Now let’s navigate to our student app’s models.py file and open it in any editor. The following lines should be included in the file:

from django.db import models

class StudentRegistration(models.Model):
    Name = models.CharField(max_length=150)
    Contact = models.CharField(max_length=15)
    Email = models.EmailField()
    Password = models.CharField(max_length=8)
    class Meta:
        db_table = "Student Registration"
  • Our StudentRegistration class contains three character fields with maximum lengths of 150, 15, and 8 characters each: Name, Contact, and Password, as well as one email field, Email.
  • We also created a Meta class and named the database table Student Registration.

Form: Once our forms.py file is created we can add the following code.

from django import forms
from .models import StudentRegistration
from matplotlib import widgets
from django.core.validators import RegexValidator

class StudentRegistrationForm(forms.ModelForm):
   Name = forms.CharField()
   Contact = forms.CharField(validators=[RegexValidator('[789][0-9]{9}', message="Enter a valid 10 digit contact number")])
   Email = forms.EmailField()
   Password = forms.CharField(widget=forms.PasswordInput)

   class Meta:
       model = StudentRegistration
       fields = "__all__"
  • Here, the field Contact has a field named validators.
  • It takes a list as an input where we are passing a method called RegexValidator.
  • The first parameter of RegexValidator is the regex value, and the second parameter is the message.
  • We define RegexValidator of Contact as
    • It must be 10 digits
    • 1st digit must be any one of the 7, 8, 9.
    • Next, 9 digits should be from 0 to 9.

Views: Once our form is ready. We can now create a new method called stud_form within our views.py file. This method will be used to register new students within the StudentRegsitration Model.

from django.shortcuts import redirect, render
from .forms import StudentRegistrationForm

def stud_form(request):  
    if request.method == "POST":  
        form = StudentRegistrationForm(request.POST)  
        if form.is_valid():  
            try:
                form.save()
                return redirect('/')  
            except:  
                pass  
    else:  
        form = StudentRegistrationForm()  
    return render(request,'form.html',{'form':form}) 

Templates: The template for the HTML file is shown below. It is stored as form.html inside the Templates Folder.

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Index</title>  
</head>  
<body>  
<form method="POST" class="post-form" enctype="multipart/form-data">  
        {% csrf_token %}  
        {{ form.as_p }}  
        <button type="submit" class="save btn btn-default">Submit</button>  
</form>  
</body>  
</html>  

Run the Server: Now, Start your application and go to the address, and type http://127.0.0.1:8000/stud_form.

Django form validation regex
Django form validation regex

We can see that when we enter a contact number that begins with 3 or when a contact number does not match the regex pattern, an error message is displayed.

Example #2

Forms: Create a form class in the forms.py file.

from django import forms
from .models import StudentRegistration
from matplotlib import widgets
from django.core.validators import RegexValidator

class StudentRegistrationForm(forms.ModelForm):
   Name = forms.CharField()
   Contact = forms.CharField()
   Email = forms.EmailField(validators=[RegexValidator('[a-zA-z0-9_\-\.]+[@][a-z]+[\.][a-z]{2,3}', message='Enter a email in correct format')])
   Password = forms.CharField(widget=forms.PasswordInput)

   class Meta:
       model = StudentRegistration
       fields = "__all__"
  • Here, the field Email has a field named validators.
  • We define RegexValidator of Email as
    • It must contains alphabets and numbers.
    • It must have @ symbol.
    • Then, it has alphabets characters.
    • Then, it follows by dot(.).
    • Then, it also contains three to two characters.

Run the Server:

Python Django form validation regex
Python Django form validation regex

We can see when an email address does not match the regex pattern, an error message is displayed.

Django form validation alphanumeric

In this section, we’ll learn form validation alphanumeric. We can set alphanumeric validation by using RegEx in Django.

Let’s see an example related to form validation alphanumeric.

From the Django form validation RegEx section follow the following steps.

  • Create Project and App
  • Install App
  • Project’s URL
  • App’s URL
  • Models
  • Views
  • Templates

Forms:

from django import forms
from .models import StudentRegistration
from matplotlib import widgets
from django.core.validators import RegexValidator

class StudentRegistrationForm(forms.ModelForm):
   Name = forms.CharField()
   Contact = forms.CharField()
   Email = forms.EmailField()
   Password = forms.CharField(widget=forms.PasswordInput, validators=[RegexValidator('[a-z]+[A-z]+[0-9]+', message='Password must be alphanumeric')])

   class Meta:
       model = StudentRegistration
       fields = "__all__"
  • Here, the field Password has a field named validators.
  • We define Regex Validator of Password as:
    • It must contains small alphabet.
    • It should have capital alphabet.
    • It also contains digits.

Run the Server:

Django form validation alphanumeric
Django form validation alphanumeric

We can see when a Password does not match the regex pattern, an error message is displayed.

Django form validation without model

In this section, we’ll learn form validation without the model in Django.

In Django, if you want to do the form validation without using a model, you have to pass forms.Form as the argument to the form class.

Syntax:

class class-name(forms.Form)

Let’s see an example:

Create Project And App: Create a project and an app by executing the below code in the terminal.

# Project
django-admin startproject Registration

# App
python manage.py startapp Employee
  • Here, we create a project Registration and an app Employee.

Install App: Now, install the above-created app in the settings.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Employee',
]

Project’s URL: In the project’s urls.py file, you have to add a link to your new app.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('Employee.urls'))
]

App’s URL: In the app’s urls.py file, you have to add the path of the function views. 

from django.urls import path,include
from . import views
urlpatterns = [
path('emp', views.emp, name='emp'),
]

Forms: In the forms.py file add the following code to create the form.

from django import forms

class EmployeeForm(forms.Form):
    Name = forms.CharField(initial = "Enter Name")
    Gender = forms.CharField(initial="Male Or Female")
    DOB = forms.DateField(initial="Enter Date of Birth")
    Designation = forms.CharField(initial="Enter Designation")
  • Here, we create Django Form EmployeeForm with fields Name, Gender, DOB, and Designation.
  • Then, we need the pre-entered text in our form fields, for this, we use the initial attribute.

View: In the views.py file add the following code to view.

from django.shortcuts import redirect, render
from .forms import EmployeeForm

def emp(request):  
    if request.method == "POST":  
        form = EmployeeForm(request.POST)  
        if form.is_valid():  
            try:  
                return redirect('/')  
            except:  
                pass  
    else:  
        form = EmployeeForm()  
    return render(request,'form.html',{'form':form})  

Templates: Now, create a forms.html template.

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Index</title>  
</head>  
<body>  
<form method="POST" class="post-form" enctype="multipart/form-data">  
        {% csrf_token %}  
        {{ form.as_p }}  
        <button type="submit" class="save btn btn-default">Submit</button>  
</form>  
</body>  
</html>

Run the Server: Start the server bypassing the http://127.0.0.1:8000/App URL in the browser.

Django form validation without model
Django form validation without model

Here, you can see that we do a form validation without using a model. And we use Django’s Built-In Validation attribute Initial to perform validation.

Also, take a look at some more Django tutorials.

In this Django tutorial, we discussed Django form validation. Also, we discussed the following lists of topics:

  • Python Django form validation
  • Django form validation example
  • Django form validation cleaned_data
  • Django form validation max_length
  • Django form validation error message
  • Django form validation checkbox
  • Django form validation required
  • Django form validation clean
  • Django form validation password
  • Djnago form validation whitespace
  • Djnago form validation integer
  • Django form validation multiple fields
  • Django form validation unique
  • Django admin form validation error
  • Django formvalidation custom
  • Django form validation exclude fields
  • Django form validation regex
  • Django form validation alphanumeric
  • Django form validation without model