0
0
Djangoframework~10 mins

Custom form validation methods in Django - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a custom clean method for the 'email' field in a Django form.

Django
def clean_[1](self):
    email = self.cleaned_data.get('email')
    if not email.endswith('@example.com'):
        raise forms.ValidationError('Email must be from example.com domain')
    return email
Drag options to blanks, or click blank then click option'
Aemail
Bcheck_email
Cvalidate_email
Dclean_email
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name that does not start with 'clean_'
Not returning the cleaned data at the end
2fill in blank
medium

Complete the code to raise a validation error if the 'age' field is less than 18.

Django
def clean_age(self):
    age = self.cleaned_data.get('age')
    if age [1] 18:
        raise forms.ValidationError('You must be at least 18 years old')
    return age
Drag options to blanks, or click blank then click option'
A<
B>=
C>
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' instead of '<'
Using '<=' which includes 18, but 18 is allowed
3fill in blank
hard

Fix the error in the custom form validation method to correctly check if the username contains spaces.

Django
def clean_username(self):
    username = self.cleaned_data.get('username')
    if ' ' [1] username:
        raise forms.ValidationError('Username cannot contain spaces')
    return username
Drag options to blanks, or click blank then click option'
Ain
Bnot in
C==
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'not in' which reverses the logic
Using '==' which compares equality, not containment
4fill in blank
hard

Fill both blanks to create a custom form validation method that checks if the password and confirm_password fields match.

Django
def clean(self):
    cleaned_data = super().[1]()
    password = cleaned_data.get('password')
    confirm = cleaned_data.get('[2]')
    if password != confirm:
        raise forms.ValidationError('Passwords do not match')
    return cleaned_data
Drag options to blanks, or click blank then click option'
Aclean
Bcleaned_data
Cconfirm_password
Dclean_password
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'cleaned_data' instead of 'clean()' for the super call
Using wrong field name for confirm password
5fill in blank
hard

Fill all three blanks to create a custom validation method that ensures the 'title' field is capitalized and at least 5 characters long.

Django
def clean_[1](self):
    title = self.cleaned_data.get('[2]')
    if len(title) [3] 5:
        raise forms.ValidationError('Title must be at least 5 characters long')
    return title.capitalize()
Drag options to blanks, or click blank then click option'
Atitle
C<
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' for length check
Using wrong method name or field name