Updated May 15, 2023
Introduction to Form Validation in Django
The following article provides an outline of Form Validation in Django. Django is a framework that offers built-in methods to verify the data in forms. Django provides methods that enable automatic verification of these changes. This verification can be performed by utilizing CSRF tokens essential for secure form submissions. Django offers functions specifically designed to handle these validations. We can here take many user inputs based on requirements and make our form validations accordingly.
Form Validations
For validating the forms, we first need to create a form and then use different validation techniques to validate the data written in the forms. For creating the form, each label would correspond to a data type with respect to the data format that must be loaded in.
Given a few of them below:
- CharField
- EmailField
- BooleanField
- DateField
- DecimalField
- ChoiceField etc.
Example of Form Validation in Django
A small example of creating a form is below:
forms.py
class MyForm(forms.Form):
Name=forms.CharField()
email=forms.EmailField(label='Email')
Gender=forms.ChoiceField(choices=[(' ','Choose'),('M','Male'),('F','Female')])
Description=forms.CharField(widget=forms.Textarea,required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper=FormHelper
self.helper.form_method = 'post'
self.helper.layout = Layout(
'Name','email','Gender','Description', Submit('submit','Submit',css_class='btn-success')
)
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import MyForm
# Create your views here.
def first_form(request):
if request.method=='POST':
form=MyForm(request.POST)
if form.is_valid():
Name=form.cleaned_data['name']
Email=form.cleaned_data['email']
Gender=form.cleaned_data['gender']
Description=form.cleaned_data['description']
print(Name,Gender)
form=MyForm()
return render(request,'form.html',{'form':form})
form.html
{% 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">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My Form </title>
</head>
<body style="padding: 20px;">
{% crispy form form.helper %}
</body>
</html>
Urls.py
from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
path('first_form',views.first_form,name='first_form'),
]
In the main project of settings.py, we need to add our new app name, and in the urls.py file also, we need to have a link of our new app that is created. Below we are adding the code snippets of those files also.
Urls.py: Project level
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('',include('Third.urls')),
path('admin/', admin.site.urls),
]
Settings.py :
We have added our app and the crispy forms module used in forms.html for styling purposes. The library can be added to a Django project using the pip install method.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Third',
'crispy_forms'
]
Using form models and HTML files specific to the forms makes it possible to create forms. In addition, forms can also be generated using the functionality models provide. Here we have done it using forms.
Upon observing the views file, we can notice the utilization of form validator methods employed here.
cleaned_data['field_name']
This is one of the important methods of validating. This would contain the cleaned data which are received from the form. This means that we are specifying a particular data type for a particular variable, which help in storing the data. We can even raise customized errors.
The main part incorporates the cleaned data function within the is_valid function.
Syntax:
form.is_valid()
Users utilize this function to validate the entire form data. They can validate whatever they upload in the form using the previously declared function. This validation would return the Boolean expressions of validating the complete form data type.
The output of the above code:
Let us check the different errors that are being raised in this simple form.
After giving the name, we try to click on submit, as shown below:
The system is going to alert error like the below:
As mentioned, the above field is mandatory; we get that alert that those fields must be filled.
Now, let’s see what we get if we directly input random letters for the email functionality.
And now, if we include the ‘@’ symbol and do not specify any domain name(not necessarily the correct one), we can still get an error.
So, after giving all the details properly as below:
It is acceptable to provide a description or leave the description field empty, as it is not mandatory. After clicking submit, we can have the below output in our Python module as written in the code.
As we wrote the code, we intended to print the name and gender. The Python development shell printed exactly that as a result. We have a link between all those Python files. Form.py file has a link with the views.py file, and in turn both are to be linked with the html file in the templates. We must have the link with urls.py and views.py to display the UI-level output through the http web URL. All Python files that generate a form and perform validations on it follow this basic flow.
For handling forms, we even have attributes like validators. When making model-level changes to a form, these methods are utilized. And even with respect to raising a customized error, it can be done by raising a ValidationError function. These functions are, by default, available in Django for different form validations. And with all these, we can even write separate functions to raise various validations concerning forms.
Conclusion
This is how we can have different form validations in Django. We have in turn, created a simple form, added our in-built validations using those respective Python files, and linked each to create perfect form validations. Many level validations can be done. But here, we have done this by creating a form and making basic validations for it. In the example mentioned above, we have covered two methods. As already listed, we can create forms using Models by models.py python file and include all the required customized validations.
Recommended Articles
We hope that this EDUCBA information on “Form Validation in Django” was beneficial to you. You can view EDUCBA’s recommended articles for more information.