python / intermediate
Snippet
Field-Specific Validation Logic in Django Forms
Django forms run `clean_<fieldname>()` methods automatically during form validation to enforce custom rules on individual fields.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
from django import formsfrom django.core.exceptions import ValidationErrorclass RegistrationForm(forms.Form):username = forms.CharField(max_length=50)def clean_username(self):data = self.cleaned_data["username"]if "admin" in data.lower():raise ValidationError("Reserved username requested.")return data
django
Breakdown
1
from django import forms
Imports the Django forms module to build standard web form definitions.
2
from django.core.exceptions import ValidationError
Imports ValidationError to raise when form inputs violate business rules.
3
class RegistrationForm(forms.Form):
Defines a custom Django Form class inheriting from forms.Form.
4
username = forms.CharField(max_length=50)
Declares a username input field with a maximum length of 50 characters.
5
def clean_username(self):
Defines a field cleaner hook targeting the username input field specifically.
6
data = self.cleaned_data["username"]
Extracts the normalized value from cleaned_data dictionary.
7
if "admin" in data.lower():
Checks if the lowercased username contains a forbidden substring.
8
raise ValidationError("Reserved username requested.")
Raises a ValidationError with a user-facing error message if invalid.
9
return data
Returns the cleaned field value to be included in cleaned_data.