Django Django Forms & Validation 2 — Questions and Answers
Question 1: How do you raise a validation error in a Django form's clean method?
- raise forms.ValidationError('message') (Correct answer)
- return forms.Invalid('message')
- raise ValueError('message')
- return None
Correct answer: raise forms.ValidationError('message')
Raising forms.ValidationError inside any clean method signals Django to mark the form as invalid and add the error to the field or non-field errors.
Question 2: What does setting `required=False` on a Django form field do?
- Makes the field optional so empty values pass validation (Correct answer)
- Hides the field from the rendered form
- Disables server-side validation for the field
- Removes the field from cleaned_data
Correct answer: Makes the field optional so empty values pass validation
By default form fields require a non-empty value; required=False allows the field to be submitted empty without triggering a validation error.
Question 3: Which Django form field is used to handle file uploads?
- FileField (Correct answer)
- UploadField
- BinaryField
- AttachmentField
Correct answer: FileField
FileField validates and handles uploaded files in forms; the HTML form must also have enctype='multipart/form-data' set.
Question 4: What is the purpose of a form's `clean()` method?
- To perform cross-field validation after individual field cleaning (Correct answer)
- To sanitize SQL injection in form data
- To reset all field values to their defaults
- To apply CSS classes to form fields
Correct answer: To perform cross-field validation after individual field cleaning
The form-level clean() method runs after all individual field clean methods and is used to validate relationships between multiple fields.
Question 5: How do you render form errors for a specific field in a Django template?
- {{ form.fieldname.errors }} (Correct answer)
- {{ form.errors.fieldname }}
- {% errors form.fieldname %}
- {{ fieldname.error }}
Correct answer: {{ form.fieldname.errors }}
Accessing form.fieldname.errors in a template returns an ErrorList of validation messages for that specific field.
Question 6: What does the `widgets` attribute in a ModelForm's Meta class do?
- Overrides the default HTML widget used to render specific fields (Correct answer)
- Adds JavaScript to form fields
- Sets CSS classes on all form inputs
- Defines custom field validators
Correct answer: Overrides the default HTML widget used to render specific fields
The widgets dict in Meta maps field names to widget classes, allowing you to customize the HTML input type rendered for each field.
How do you raise a validation error in a Django form's clean method?