Django — Form Validation
Validation Methods
class RegistrationForm(forms.Form):
username = forms.CharField(max_length=50)
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput)
def clean_username(self):
username = self.cleaned_data['username']
if User.objects.filter(username=username).exists():
raise forms.ValidationError("Username already taken")
return username
def clean_email(self):
email = self.cleaned_data['email']
if not email.endswith('@example.com'):
raise forms.ValidationError("Must be example.com email")
return email
def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get('password')
confirm = cleaned_data.get('confirm_password')
if password and confirm and password != confirm:
raise forms.ValidationError("Passwords don't match")
return cleaned_data
Validation Flow
clean_<fieldname>()— Single fieldclean()— Whole formvalidate_<fieldname>()— Custom validators
Built-in Validators
from django.core.validators import (
MinValueValidator, MaxValueValidator,
MinLengthValidator, RegexValidator,
URLValidator, EmailValidator
)
age = forms.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(120)])
Error Handling
if form.is_valid():
# Process valid data
else:
# Access errors
print(form.errors)
print(form.errors.as_json())
print(form.errors.as_text())
Mini Practice
- Create a form with field validation
- Add cross-field validation
- Display validation errors
- Use built-in validators
Up Next
Continue with Static Files — serving CSS, JavaScript, and images.
Related Topics
Frequently Asked Questions about Form Validation
What is Form Validation in Django?
Form Validation is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Form Validation?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Form Validation.
Why is Form Validation important in Django?
Form Validation is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.