0
0
Djangoframework~5 mins

Form validation (is_valid, cleaned_data) in Django

Choose your learning style9 modes available
Introduction

Form validation helps check if the data a user enters is correct and safe before saving or using it. It stops mistakes and bad data from causing problems.

When you want to check if a user filled out a form correctly before saving their info.
When you need to clean or change user input to a safe or standard format.
When you want to show error messages if the user missed something or typed wrong.
When you want to get the cleaned, safe data from a form after checking it.
Syntax
Django
form = MyForm(request.POST)
if form.is_valid():
    data = form.cleaned_data
    # use data safely
else:
    # handle errors

is_valid() checks all fields and returns True if data is good.

cleaned_data holds the safe, cleaned data after validation.

Examples
Check if the form is valid, then get the cleaned name and email.
Django
form = ContactForm(request.POST)
if form.is_valid():
    name = form.cleaned_data['name']
    email = form.cleaned_data['email']
If the form is not valid, get the errors to show to the user.
Django
form = SignupForm(request.POST)
if not form.is_valid():
    errors = form.errors
Use get to safely access a field that might be optional.
Django
form = FeedbackForm(request.POST)
if form.is_valid():
    message = form.cleaned_data.get('message', '')
Sample Program

This example creates a simple form with name and age fields. It checks if the data is valid and prints the cleaned data. If invalid, it prints errors.

Django
from django import forms

class SimpleForm(forms.Form):
    name = forms.CharField(max_length=10)
    age = forms.IntegerField(min_value=0, max_value=120)

# Simulate POST data
post_data = {'name': 'Alice', 'age': '30'}

form = SimpleForm(post_data)

if form.is_valid():
    cleaned = form.cleaned_data
    print(f"Name: {cleaned['name']}")
    print(f"Age: {cleaned['age']}")
else:
    print("Errors:", form.errors)
OutputSuccess
Important Notes

Always call is_valid() before accessing cleaned_data.

If is_valid() returns False, cleaned_data is not available.

Use form errors to help users fix their input.

Summary

Use is_valid() to check if form data is good.

Access safe data with cleaned_data after validation.

Show errors if validation fails to guide users.