Challenge - 5 Problems
Form Error Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What happens when a Django form is invalid?
Consider a Django form instance that has been submitted with invalid data. What will be the state of
form.errors and what will the template typically display?Django
form = MyForm(data=request.POST) if not form.is_valid(): errors = form.errors
Attempts:
2 left
💡 Hint
Think about how Django helps users know what went wrong with their input.
✗ Incorrect
When a Django form is invalid, form.errors holds a dictionary mapping each field to its list of error messages. Templates can access these to show errors next to each field, guiding the user.
📝 Syntax
intermediate2:00remaining
Which code correctly adds a non-field error to a Django form?
You want to add a custom error message that is not tied to any specific field. Which code snippet correctly does this inside a Django form's
clean() method?Django
def clean(self): cleaned_data = super().clean() if some_condition: # add non-field error here return cleaned_data
Attempts:
2 left
💡 Hint
Check Django docs for adding errors not tied to fields.
✗ Incorrect
Using self.add_error(None, message) adds a non-field error properly. Other options are invalid or cause errors.
🔧 Debug
advanced2:00remaining
Why does this Django form not show errors in the template?
Given this view code snippet, why might the form errors not appear in the template?
form = MyForm(request.POST or None)
if form.is_valid():
# process data
else:
form = MyForm()Attempts:
2 left
💡 Hint
Look at how the form variable is assigned in the else block.
✗ Incorrect
Reassigning form = MyForm() in the else block creates a new empty form without errors, so the template sees no errors to display.
❓ state_output
advanced2:00remaining
What is the output of this Django form error check?
Consider this code snippet inside a Django form's
What will
clean() method:if self.cleaned_data.get('age', 0) < 18:
self.add_error('age', 'Must be at least 18')
return self.cleaned_dataWhat will
form.errors contain if the submitted age is 16?Attempts:
2 left
💡 Hint
Check how add_error associates messages with fields.
✗ Incorrect
The error is added to the 'age' field, so form.errors will have a key 'age' with the message.
🧠 Conceptual
expert2:00remaining
Which statement about Django form error handling is true?
Select the one true statement about how Django handles form errors during validation.
Attempts:
2 left
💡 Hint
Think about how Django separates errors for fields and general form errors.
✗ Incorrect
Django keeps field errors keyed by field name in form.errors. Non-field errors appear under the special key __all__. Other options are incorrect.