Django Form Validation Best Practices
Q: How do you handle form validation in Django? Can you provide an example of how you would write a custom validation method?
- Django
- Mid level question
Explore all the latest Django interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Django interview for FREE!
In Django, form validation is performed automatically when a
form is submitted. However, developers can also write custom validation methods
to perform additional validation checks or to validate fields that are not part
of the form.
Here's an example of how you would write a custom validation
method for a Django form:
from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea) def clean_message(self): message = self.cleaned_data['message'] num_words = len(message.split()) if num_words < 5: raise forms.ValidationError("Message must contain at least 5 words.") return message
In this example, we define a form called ContactForm
that includes three fields: name, email, and message. We
also define a custom validation method called clean_message that checks
that the message field contains at least 5 words.
The cleaned_data dictionary is automatically
generated by Django when the form is submitted and contains the cleaned values
of the form fields. In our custom validation method, we retrieve the cleaned
value of the message field and split it into words using the split
method. We then check that the number of words is at least 5 and raise a forms.ValidationError
if it is not.
To display the validation error message in the template, we
can include the {{ field.errors }} template tag next to the form field,
like this:
<form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form>
In this example, the {{ form.as_p }} template tag
generates HTML markup for the form, including the validation error message if
the form fails validation.
By using custom validation methods, developers can perform
additional validation checks or customize the validation behavior of Django's built-in
form fields.


