Users Online

· Guests Online: 45

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Articles Hierarchy

Django Tutorial

Form Validation in Django

Form Validation in Django

Introduction to Form Validation in Django

The following article provides an outline on Form Validation in Django. Django is a framework which provides built in methods to verify the data within in forms. And this verification can be done automatically using these Django methods. These can be only done by using and submitting CSRF tokens. There are functions that can be used to handle these validations. We can here take many inputs from user based on requirement 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 format of data that has to be loaded in.

Given few of them below:

  • CharField
  • EmailField
  • BooleanField
  • DateField
  • DecimalField
  • ChoiceField etc.

Example of Form Validation in Django

A small example of creating a form 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 that we have used in forms.html for styling purpose. That library can be added into Django using 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'
]

Forms can be created using form models and the forms html files and at the same time with the models functionality also. Here we have done it using forms.

When observed, we can see that in views file that is written, there were form validator methods that we have used 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 of the data. We can even raise customized errors.

The main part, in which cleaned data function, is incorporated under function is_valid.

Syntax:

form.is_valid()

This function is used to validate the whole form data. Whatever is uploaded in the form can be validated using this function that is declared above. This validation would be returning the Boolean expressions of validating the complete form data type.

Output of the above code:

form validation in django 1

Let us check the different errors that are being raised in this simple form.

After giving the name, if we simply try to click on submit as shown below:

form validation in django 2

System is going to alert error like below:

System is going to alert error

As we have mentioned the above field mandatory we get that alert that those fields has to be filled.

Now with respect to the email functionality, if we give some random letters directly let us see what we get.

form validation in django 8

And now if we include the ‘@’ symbol also and if we do not specify any domain name(not necessarily the correct one), we can still get an error.

form validation in django 9

So, after giving all the details properly as below:

giving all the details properly

It is okay to either write anything or leave the description part empty as it is not the mandatory required field. After clicking on submit we can have the below output in our python module as written in the code.

form validation in django 7

As written the code, we wanted to print the name and gender – so that is what that got printed in our python development shell. We have link between all those python files. Form.py file has link with views.py file and in turn both are to be linked with the html file in the templates. As already known we must have the link with urls.py and views.py to display the UI level output through the http web URL. This is the basic flow for all those python files that are written in generating a form and performing it’s vaLidations.

For handling forms, we even have attributes like validators. These are used in case of model level changes to a form. And even with respect to raising a customized error can be done by raising a ValidationError function. These are the functions that are in default available in Django for different form validations. And with all these we can even have separate functions written to raise different validations with respect to 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 link each of them to create perfect form validations. There are many level validations that can be done. But here we have done by creating a form and making basic validations for it. We have covered two methods in the same example which is mentioned above. As already listed, we can create forms using Models by models.py python file and include all the customized validations that are required.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.76 seconds
10,842,427 unique visits