Django Django Forms & Validation 1 — Questions and Answers
Question 1: What class do you subclass to create a Django form?
- forms.Form (Correct answer)
- forms.BaseForm
- forms.ModelForm
- forms.Field
Correct answer: forms.Form
forms.Form is the base class for creating standard Django forms with manually defined fields, separate from any model.
Question 2: What is a Django ModelForm?
- A form that automatically generates fields from a Django model (Correct answer)
- A form stored in the database
- A form rendered using model templates
- A form that validates against a model schema
Correct answer: A form that automatically generates fields from a Django model
ModelForm creates form fields based on a model's field definitions, reducing duplication by using the model as the source of truth for field types and validators.
Question 3: Which method checks if a submitted Django form is valid?
- form.is_valid() (Correct answer)
- form.validate()
- form.check()
- form.clean()
Correct answer: form.is_valid()
is_valid() runs all field-level and form-level validation, populates form.cleaned_data if successful, and returns True or False.
Question 4: Where is validated form data stored after calling `form.is_valid()`?
- form.cleaned_data (Correct answer)
- form.data
- form.valid_data
- form.post_data
Correct answer: form.cleaned_data
form.cleaned_data is a dictionary populated by is_valid() that contains the validated and type-coerced form field values.
Question 5: How do you define custom validation for a single field in a Django form?
- Define a method named clean_<fieldname>(self) (Correct answer)
- Override the validate() method
- Add a validator= argument to the field
- Subclass the field class
Correct answer: Define a method named clean_<fieldname>(self)
A method named clean_fieldname() is automatically called by is_valid() for that field and can raise ValidationError or return the cleaned value.
Question 6: What does `form.save()` do on a Django ModelForm?
- Creates or updates the model instance based on the form's cleaned data (Correct answer)
- Saves the form HTML to a file
- Stores form data in the session
- Persists form errors to the database
Correct answer: Creates or updates the model instance based on the form's cleaned data
ModelForm.save() creates a new instance or updates an existing one (if bound to an instance) using the validated cleaned_data.
What class do you subclass to create a Django form?