Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Django Form Validation

In this article, we will learn about the Built-In Django Form Validation offered as well as the Django Custom Form Validations.

Prerequisites for Django Form Validation

Before moving forward with Form Validation, you will need to know what Django forms and how you implement them in Django.

If you are already familiar with Django Forms, then continue with the article or else do check out Django Forms article first.

Built-In Form Validations

Django framework provides a list of built-in form validators along with the Forms library. We will learn about each one of them here.

Setting up a Form and Using Built-in Validators

Field = forms.Field_Type(validator = value)

All of the built-in validators follow the above syntax.

The Form View used in this section

The following explanation codes are based on the following View in views.py

def EFormView(request):
    if request.method == 'POST':
        form = EForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse('Form saved')
    else:
        form = EForm()
        context = {
            'form':form,
        }
    return render(request, 'books_website/Form.html', context)

And the Template is a simple HTML file including the form attribute of HTML

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

1. initial – Placeholder Text with the “Initial” Attribute

You might have seen many forms on the internet come with a pre-entered text like the one given below.

Example
Example

This is done using the initial attribute of Django Forms.

Therefore, if you need a pre-entered text in your form fields, we use the initial attribute.

The initial default value is empty. 

class EForm(forms.Form):
    Name = forms.CharField(initial = "Enter Name")
Initial
Initial

2. label – Adding Labels to a Form Field

The label attribute gives a custom name to the form field. As a default, Django uses the form field name specified in forms.py itself as the field name. But using label we can change it to any other custom name.

class EForm(forms.Form):
    Name = forms.CharField(label = "Full Name")
Label
Label

3. max_length – Limit Maximum Length of Characters Entered

The max_length attribute ensures that the information entered in the field does not exceed more than the specified value.

class EForm(forms.Form):
    username = forms.CharField(max_length = 10)
Max Length
Max Length

Note that you wont be able to add more than 10 characters.

4. error_message – Add a Custom Error Message

The error_message attribute lets you add custom error messages to the fields. This attribute overrides the default error message and enables you to write your own.

The error message is passed as a dictionary, as shown:

class EForm(forms.Form):
    username = forms.CharField(error_message = {'required':'Please Enter your Name',})
Image 26
Error Message

5. disabled – Add Uneditable Values to Django Forms

In many forms, specific fields are uneditable by users like the company’s name on specific company forms.

The disabled attribute lets you do that. Using this, you can disable a particular field, thereby leaving it uneditable by the user.

class ITJobForm(forms.Form):
    Interview domain = forms.CharField(disabled = True, initial = 'Software Engineer')
    Name = forms.CharField(max_length = 80)
Disabled
Disabled

Note that you wont be able to change the value for the Interview domain field.

6. help_text – Suggest What Needs to be Entered in the Input

This attribute adds a help text beside the field to give more information about what has to be entered.

class EForm(forms.Form):
    Name = forms.CharField(help_text ='Please enter your name')
Help Text
Help Text

7. required – Ensure a Form Field has Data Before Submitting

In many forms, certain fields are compulsory, like the applicant’s name, number, etc. This is done with the required attribute.

Default value is False

class EForm(forms.Form):
    Name = forms.CharField(required = True)
Fullscreen 1
Required

8. widget – Set up Individual Form Fields for Predefined Purposes

Widget is Django’s representation of HTML input. Each field has its predefined field widget. For example, a Number Field will have a widget taking only number input, email field taking only the email input, etc.

We can override the default widgets and add our own as shown:

class EForm(forms.Form):
    Name = forms.CharField(widget = forms.Textarea)
Widget
Widget

Custom Form Validation using ValidationError attribute

As seen in the Django exception handling article, the Validation Error attribute is used to validate custom form information entered by the user.

The syntax for using Validation Error

ValidationError('text',params = {value : <value>})

Here, the value variable and the text depends on where we are calling the attribute and also on the condition for validation.

The full syntax for ValidationError is:

import django.core.exceptions
if cond:
    raise ValidationError('text')

Implementing of Custom Validations 

Lets us create a form that allows username to be between 10 to 20 characters only. The form.py code will be:

class EForm(forms.Form):
    Name = forms.CharField(label = "Full Name")

Add the Form View Code as shown:

from django.core.exceptions import ValidationError
def FormView(request):
    if request.method == 'POST':
        form = EForm(request.POST)
        if form.is_valid():
            Name = form.cleaned_data['Name']
            if len(Name)< 10 or len(Name) > 20:
                raise ValidationError(f'Length of the name:{Name} is not between 10 -20 characters')
            return HttpResponse('Form saved')
    else:
        form = EForm()
        context ={
            'form':form
        }
    return render(request,'books_website/Form.html',context)

Notice how the Validation Error is raised. The template is the same as the one seen above.

Let’s run the server and enter a name with less than 10 characters. You can also try the same with more than 10 characters as it still voids our condition.

Validation Error 1
Validation Error

When you hit submit, you’ll get an error as shown below:

Error
Form Error

Now we will try for a name in between 10 to 20 characters

Form 10
Form 11 characters

Hit submit and check

Saved
Form Saved

See how the form accepts only certain names. This is how a ValidationError works.

Conclusion

That’s it, guys !! This was all about form validation. Also, check out the official Django forms documentation for more information. Keep practicing!!