Django

Implement Custom Validation using clean() Method in forms.py

๐Ÿ“Œ 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 validation
  • cleaned_data contains validated values
  • ValidationError is 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

  1. User fills the registration form
  2. Form is submitted via POST
  3. Django validates individual fields
  4. clean() method applies custom logic
  5. If error โ†’ ValidationError shown
  6. 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

  1. Add email + confirm email validation
  2. Check username length โ‰ฅ 5
  3. Prevent numeric-only usernames
  4. Add password strength validation
  5. 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

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *