0
0
Djangoframework~10 mins

Custom form validation methods in Django - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Custom form validation methods
Start form submission
Call form.is_valid()
Run built-in validations
Run custom clean_<field>() methods
Run form's clean() method
Collect errors or accept data
Return validation result
When a form is submitted, Django runs built-in checks, then custom field validations, then overall form validation before accepting or rejecting data.
Execution Sample
Django
from django import forms

class MyForm(forms.Form):
    age = forms.IntegerField()

    def clean_age(self):
        age = self.cleaned_data['age']
        if age < 18:
            raise forms.ValidationError('Must be 18 or older')
        return age
This form checks if the age field is 18 or older using a custom validation method.
Execution Table
StepActionEvaluationResult
1Call form.is_valid()Trigger validationStart validation process
2Run built-in validationsCheck age is integer and requiredPass if valid integer
3Run clean_age()Check if age < 18Raise error if true, else pass
4Run clean()No extra checks herePass
5Collect errorsIf any errors, form.is_valid() returns FalseForm invalid if errors exist
6Return validation resultNo errors foundForm is valid
💡 Validation stops after all checks; errors cause form.is_valid() to be False
Variable Tracker
VariableStartAfter Step 2After Step 3Final
ageNone25 (input parsed)25 (validated)25 (cleaned)
errors{}{}{}{}
Key Moments - 3 Insights
Why does clean_age() raise ValidationError instead of returning False?
In execution_table step 3, raising ValidationError signals Django to mark the field invalid and show the error message. Returning False would not trigger this behavior.
When is the form's clean() method called compared to clean_<field>()?
As shown in execution_table step 4, clean_<field>() methods run first for each field, then clean() runs once for the whole form to check combined data.
What happens if built-in validation fails before custom methods?
In step 2, if built-in validation fails (e.g., age not an integer), custom methods like clean_age() are not called, and form.is_valid() returns False immediately.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at step 3 if age is 16?
Aclean_age() passes without error
Bbuilt-in validation fails
Cclean_age() raises ValidationError
Dform.is_valid() returns True immediately
💡 Hint
See step 3 where clean_age() checks if age < 18 and raises error if true
At which step does Django collect all errors to decide if form is valid?
AStep 5
BStep 3
CStep 2
DStep 6
💡 Hint
Step 5 is labeled 'Collect errors' in the execution_table
If the input for age is 'abc', what changes in the execution_table?
Aclean_age() raises ValidationError
BStep 2 fails built-in validation, clean_age() not called
Cclean() method raises error
Dform.is_valid() returns True
💡 Hint
Refer to key_moments 3 and step 2 in execution_table about built-in validation
Concept Snapshot
Custom form validation in Django:
- Define clean_<field>() to validate individual fields
- Raise ValidationError to signal invalid data
- clean() method validates whole form after fields
- form.is_valid() runs all validations and collects errors
- Validation stops early if built-in checks fail
Full Transcript
When you submit a Django form, the system first runs built-in checks like required fields and data types. Then it calls any custom clean_<field>() methods you wrote to check specific fields. If those pass, it runs the form's clean() method to check the whole form together. If any validation fails, Django collects errors and form.is_valid() returns False. If all checks pass, form.is_valid() returns True and you can use the cleaned data safely.