Form Validation
In this page:
Checking Validity
is_valid() runs all field validators and returns True only if every field passes.
Example: Checking Validity
is_valid() runs all field validators and returns True only if every field passes.
form = ContactForm(request.POST)
if form.is_valid():
print(form.cleaned_data['email'])
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
Reading Cleaned Data
cleaned_data is a dictionary of validated, type-converted values, only available after is_valid() succeeds.
Example: Reading Cleaned Data
cleaned_data is a dictionary of validated, type-converted values, only available after is_valid() succeeds.
form = ContactForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
Displaying Errors
When validation fails, form.errors holds a dictionary of field names to error messages, shown automatically by {{ form.as_p }}.
Example: Displaying Errors
When validation fails, form.errors holds a dictionary of field names to error messages, shown automatically by {{ form.as_p }}.
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
- Reading request.POST values directly instead of calling form.is_valid() first, skipping validation entirely.
- Accessing form.cleaned_data before calling is_valid(), which raises an error because cleaning hasn't run yet.
- Assuming client-side HTML5 validation (like required) is enough, ignoring that the server must always re-validate.
- Calling form.is_valid() runs every field's validation and populates form.cleaned_data on success.
- Invalid submissions automatically attach error messages to form.errors for each bad field.
- Never trust data straight from request.POST — always validate through the form first.
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: