0
0
Djangoframework~30 mins

Custom form validation methods in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom form validation methods
📖 Scenario: You are building a simple Django web app where users submit their profile information through a form. You want to make sure the data they enter is valid before saving it.
🎯 Goal: Create a Django form with custom validation methods to check user input for specific rules.
📋 What You'll Learn
Create a Django form class called UserProfileForm with fields username and age.
Add a custom validation method to check that username is at least 5 characters long.
Add a custom validation method to check that age is at least 18.
Raise appropriate validation errors if the rules are not met.
💡 Why This Matters
🌍 Real World
Custom form validation is essential in web apps to ensure users enter correct and safe data before saving it to the database.
💼 Career
Understanding how to write custom validation methods in Django forms is a key skill for backend web developers working with user input and data integrity.
Progress0 / 4 steps
1
Create the initial form class with fields
Create a Django form class called UserProfileForm that inherits from forms.Form. Add two fields: username as a forms.CharField and age as a forms.IntegerField.
Django
Need a hint?

Use class UserProfileForm(forms.Form): to start the form class. Add fields as class variables.

2
Add a custom validation method for username length
Inside the UserProfileForm class, add a method called clean_username that checks if the username is at least 5 characters long. If it is shorter, raise forms.ValidationError with the message 'Username must be at least 5 characters long.'. Return the cleaned username if valid.
Django
Need a hint?

Define clean_username(self) method. Use self.cleaned_data['username'] to get the value.

3
Add a custom validation method for minimum age
Inside the UserProfileForm class, add a method called clean_age that checks if the age is at least 18. If it is less, raise forms.ValidationError with the message 'You must be at least 18 years old.'. Return the cleaned age if valid.
Django
Need a hint?

Define clean_age(self) method. Use self.cleaned_data['age'] to get the value.

4
Complete the form with all validations
Ensure the UserProfileForm class includes both clean_username and clean_age methods with the validations as described. The form should be ready to use in a Django view for validation.
Django
Need a hint?

Make sure both validation methods are present and correctly implemented.