Interview question
How does Django form validation work with clean_() and clean()?
Django form validation clean_() और clean() से कैसे काम करता है?
Answer
| Method | Validates | When to use |
|---|---|---|
| clean_<fieldname>() | A single specific field | Field-specific rules (format, uniqueness) |
| clean() | The whole form, across multiple fields | Cross-field validation (e.g. password confirmation) |
from django import forms
from django.core.exceptions import ValidationError
class SignupForm(forms.Form):
username = forms.CharField(max_length=30)
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput)
email = forms.EmailField()
# FIELD-level validation - runs automatically for the 'username' field
def clean_username(self):
username = self.cleaned_data['username']
if User.objects.filter(username=username).exists():
raise ValidationError('This username is already taken')
return username # MUST return the (possibly modified) cleaned value
def clean_email(self):
email = self.cleaned_data['email']
if not email.endswith('@company.com'):
raise ValidationError('Must use a company email address')
return email
# FORM-level validation - runs AFTER all field-level clean_X methods
def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get('password')
confirm_password = cleaned_data.get('confirm_password')
if password and confirm_password and password != confirm_password:
# attach the error to a specific field, or use None for a
# general (non-field) error shown at the top of the form
self.add_error('confirm_password', 'Passwords do not match')
return cleaned_data
# Validation execution order:
# 1. Field's built-in validators (e.g. EmailField's format check)
# 2. clean_<fieldname>() for each field with one defined
# 3. Form's clean() method for cross-field validation
form = SignupForm(request.POST)
if form.is_valid():
# all validation passed, form.cleaned_data has clean values
pass
else:
print(form.errors) # dict of field -> list of error messages| Method | क्या validate करता है | कब use करें |
|---|---|---|
| clean_<fieldname>() | एक specific field | Field-specific rules |
| clean() | पूरा form, कई fields में | Cross-field validation |
from django import forms
from django.core.exceptions import ValidationError
class SignupForm(forms.Form):
username = forms.CharField(max_length=30)
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput)
email = forms.EmailField()
def clean_username(self):
username = self.cleaned_data['username']
if User.objects.filter(username=username).exists():
raise ValidationError('यह username पहले से लिया गया है')
return username
def clean_email(self):
email = self.cleaned_data['email']
if not email.endswith('@company.com'):
raise ValidationError('Company email address ज़रूरी है')
return email
def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get('password')
confirm_password = cleaned_data.get('confirm_password')
if password and confirm_password and password != confirm_password:
self.add_error('confirm_password', 'Passwords match नहीं करते')
return cleaned_data
form = SignupForm(request.POST)
if form.is_valid():
pass
else:
print(form.errors)Was this answer clear?