Consider a Django form with a clean_email() method that raises ValidationError if the email is invalid. What is the effect on the form's behavior when this error is raised?
from django import forms class EmailForm(forms.Form): email = forms.EmailField() def clean_email(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
Think about how Django handles validation errors in field-specific clean methods.
When clean_ raises ValidationError, Django marks the form as invalid and attaches the error message to that field. This prevents form submission until corrected.
Given a Django form with a custom clean() method that modifies cleaned_data, what will be the final value of cleaned_data after is_valid() is called?
from django import forms class NameForm(forms.Form): first_name = forms.CharField() last_name = forms.CharField() def clean(self): cleaned_data = super().clean() first = cleaned_data.get('first_name') last = cleaned_data.get('last_name') if first and last: cleaned_data['full_name'] = f'{first} {last}' return cleaned_data form = NameForm({'first_name': 'Jane', 'last_name': 'Doe'}) form.is_valid() result = form.cleaned_data.get('full_name')
Remember that clean() can add new keys to cleaned_data.
The clean() method adds a new key full_name combining first and last names. After validation, cleaned_data includes this key with value 'Jane Doe'.
Identify the correct syntax for a custom clean_ method in a Django form to validate the username field.
from django import forms class UserForm(forms.Form): username = forms.CharField() # Custom validation method here
Custom field clean methods take only self and access data from self.cleaned_data.
The correct method signature is def clean_fieldname(self):. It accesses the field value from self.cleaned_data. Option C follows this pattern correctly.
Examine the following Django form code. Why does calling is_valid() raise a KeyError?
from django import forms class ProfileForm(forms.Form): age = forms.IntegerField() def clean(self): cleaned_data = super().clean() if cleaned_data['age'] < 18: raise forms.ValidationError('Must be at least 18') return cleaned_data form = ProfileForm({'age': ''}) form.is_valid()
Think about what happens when a required field is empty before clean() runs.
If the 'age' field is empty or invalid, it is not included in cleaned_data. Accessing cleaned_data['age'] then raises a KeyError. The code should use cleaned_data.get('age') and check for None.
Choose the correct statement about how Django handles custom validation methods in forms.
Consider the order Django calls validation methods and their roles.
Django calls all clean_ methods first, then calls clean(). The clean() method can access and modify all fields' data together. ValidationErrors in field methods do not stop clean() from running.