๐ Introduction
Django provides built-in validations like:
- required fields
- email format
- min/max length
But sometimes we need custom validation, such as:
- password match
- age restriction
- comparing multiple fields
๐ For this, Django provides the clean() method.
๐ฏ Program Statement
๐ Implement custom validation using clean() method in forms.py.
๐ง Concept
This program demonstrates:
- form with multiple fields
- custom validation using
clean() - raising validation errors
- displaying error messages
โ๏ธ Step 1: Create Form with Custom Validation
๐ File: forms.py
๐น Path:
myproject/myapp/forms.py
๐น Code:
from django import forms
class RegistrationForm(forms.Form):
username = forms.CharField(label='Enter Username', max_length=100)
age = forms.IntegerField(label='Enter Age')
password = forms.CharField(label='Enter Password', widget=forms.PasswordInput)
confirm_password = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super().clean()
age = cleaned_data.get('age')
password = cleaned_data.get('password')
confirm_password = cleaned_data.get('confirm_password')
# Custom Validation 1: Age must be >= 18
if age is not None and age < 18:
raise forms.ValidationError("Age must be at least 18.")
# Custom Validation 2: Password match
if password and confirm_password:
if password != confirm_password:
raise forms.ValidationError("Passwords do not match.")
return cleaned_data
๐ง Explanation
clean()method is used for cross-field validationcleaned_datacontains validated valuesValidationErroris raised when condition fails
โ๏ธ Step 2: Create View
๐ File: views.py
๐น Path:
myproject/myapp/views.py
๐น Code:
from django.shortcuts import render
from .forms import RegistrationForm
def register(request):
success = False
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
success = True
else:
form = RegistrationForm()
return render(request, 'register.html', {
'form': form,
'success': success
})
๐ง Explanation
- If validation passes โ success message shown
- If validation fails โ error messages displayed automatically
โ๏ธ Step 3: URL Mapping
๐ File: urls.py
๐น Path:
myproject/myproject/urls.py
๐น Code:
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', views.register, name='register'),
]
โ๏ธ Step 4: Create Template
๐ File: register.html
๐น Path:
myproject/templates/register.html
๐น Code:
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h1>Registration Form</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
<hr>
{% if success %}
<h2 style="color: green;">Registration Successful!</h2>
{% endif %}
</body>
</html>
๐ง Explanation
- Form errors are automatically displayed
- If validation passes โ success message shown
โ๏ธ Step 5: Run Server
python manage.py runserver
๐ Step 6: Output
๐ http://127.0.0.1:8000/register/
โ Case 1: Age < 18
Age must be at least 18.
โ Case 2: Password mismatch
Passwords do not match.
โ Valid Input
- Username: Charlie
- Age: 12
- Password: 1234
- Confirm Password: 1234
Registration Successful!
๐ง How It Works
- User fills the registration form
- Form is submitted via POST
- Django validates individual fields
clean()method applies custom logic- If error โ ValidationError shown
- If success โ message displayed
๐ฅ Key Concepts
clean() Method
def clean(self):
Used for validating multiple fields together.
Accessing Data
cleaned_data.get('field_name')
Safely retrieves values.
Raising Error
raise forms.ValidationError("Error message")
Stops form submission and shows error.
Password Input
widget=forms.PasswordInput
Hides typed characters.
โ ๏ธ Common Errors
โ Not calling super().clean()
cleaned_data = super().clean()
๐ Must be included
โ Using clean() for single field
๐ Use clean_fieldname() for single-field validation
โ Forgetting return
return cleaned_data
โ Incorrect field names
cleaned_data.get('password')
Must match form field names exactly
๐งช Practice Questions
- Add email + confirm email validation
- Check username length โฅ 5
- Prevent numeric-only usernames
- Add password strength validation
- Restrict age between 18 and 60
๐ค Viva Questions & Answers
1. What is the clean() method in Django?
The clean() method is used for custom validation involving multiple fields in a form.
2. Why is clean() needed when Django already provides validation?
Built-in validation handles individual fields, but clean() is used when validation depends on multiple fields.
3. What is cleaned_data?
cleaned_data is a dictionary containing validated form data after is_valid() is called.
4. What is ValidationError?
It is used to raise validation errors when custom conditions fail.
5. What happens if ValidationError is raised?
The form becomes invalid, and error messages are displayed to the user.
6. Why do we use super().clean()?
It ensures that built-in validation is executed before custom validation.
7. Can we validate a single field using clean()?
No, for single-field validation we should use clean_fieldname() method.
8. What is the use of PasswordInput widget?
It hides the password while typing for security.
๐ Next Section: Django Models & Database Operations
๐ Back to List: Django Programs (60 Questions with Solutions)
Further Reading
Introduction to Django Framework and its Features
Examples of Array Functions in PHP
Registration Form Using PDO in PHP
Inserting Information from Multiple CheckBox Selection in a Database Table in PHP
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
