0
0
Djangoframework~30 mins

Form validation (is_valid, cleaned_data) in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Form validation (is_valid, cleaned_data)
📖 Scenario: You are building a simple Django web app where users can submit their name and age through a form.We want to check if the form data is valid and then access the cleaned data safely.
🎯 Goal: Create a Django form with fields for name and age. Then validate the form using is_valid() and access the cleaned data using cleaned_data.
📋 What You'll Learn
Create a Django form class called PersonForm with name (CharField) and age (IntegerField).
Create a dictionary called form_data with 'name': 'Alice' and 'age': 30.
Instantiate PersonForm with form_data.
Check if the form is valid using form.is_valid() and then access form.cleaned_data.
💡 Why This Matters
🌍 Real World
Forms are used in web apps to collect user input like registration, login, or surveys. Validating forms ensures data is correct before saving or processing.
💼 Career
Understanding Django form validation is essential for backend web developers working with user input and data integrity.
Progress0 / 4 steps
1
Create the form data dictionary
Create a dictionary called form_data with these exact entries: 'name': 'Alice' and 'age': 30.
Django
Need a hint?

Use curly braces {} to create a dictionary with keys 'name' and 'age'.

2
Create the PersonForm class
Create a Django form class called PersonForm that inherits from forms.Form. Add a name field as forms.CharField() and an age field as forms.IntegerField(). Import forms from django.
Django
Need a hint?

Use class PersonForm(forms.Form): and define fields inside the class.

3
Instantiate the form with data and validate
Create a variable called form and instantiate PersonForm with form_data. Then check if the form is valid using form.is_valid().
Django
Need a hint?

Call PersonForm(form_data) to create the form instance, then call form.is_valid().

4
Access the cleaned data after validation
After confirming the form is valid, create a variable called cleaned and assign it the value of form.cleaned_data.
Django
Need a hint?

Use an if statement to check valid before accessing cleaned_data.