form.errors and what will the template typically display?form = MyForm(data=request.POST) if not form.is_valid(): errors = form.errors
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.
clean() method?def clean(self): cleaned_data = super().clean() if some_condition: # add non-field error here return cleaned_data
Using self.add_error(None, message) adds a non-field error properly. Other options are invalid or cause errors.
form = MyForm(request.POST or None)
if form.is_valid():
# process data
else:
form = MyForm()Reassigning form = MyForm() in the else block creates a new empty form without errors, so the template sees no errors to display.
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?The error is added to the 'age' field, so form.errors will have a key 'age' with the message.
Django keeps field errors keyed by field name in form.errors. Non-field errors appear under the special key __all__. Other options are incorrect.
