Challenge - 5 Problems
ModelForm Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What happens when a ModelForm is saved without commit?
Consider a Django ModelForm instance created with
commit=False in the save() method. What is the state of the returned object?Django
form = MyModelForm(request.POST) if form.is_valid(): obj = form.save(commit=False) # What is true about obj here?
Attempts:
2 left
💡 Hint
Think about what commit=False means in Django ModelForm save method.
✗ Incorrect
Using commit=False creates a model instance but does not save it to the database. This allows you to modify the object before saving.
📝 Syntax
intermediate2:00remaining
Which ModelForm field declaration is correct for excluding a model field?
You want to create a ModelForm that excludes the
created_at field from the form. Which of the following Meta class declarations is correct?Django
class MyModelForm(forms.ModelForm): class Meta: model = MyModel # Choose the correct way to exclude 'created_at'
Attempts:
2 left
💡 Hint
The exclude attribute expects a list of field names.
✗ Incorrect
The exclude attribute in the Meta class should be a list of field names to omit from the form.
🔧 Debug
advanced3:00remaining
Why does this ModelForm raise a ValidationError on save?
Given this ModelForm code, why does calling
form.save() raise a ValidationError even though form.is_valid() returned True?Django
class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['name'] form = MyModelForm(data={'name': 'Alice'}) if form.is_valid(): form.save()
Attempts:
2 left
💡 Hint
Check which fields are required by the model and which are provided in the form data.
✗ Incorrect
The form is valid because it only validates fields declared in fields. However, the model requires 'email' which is missing, so saving fails.
❓ state_output
advanced2:00remaining
What is the value of form.errors after invalid submission?
A ModelForm is submitted with missing required fields. What does
form.errors contain after calling form.is_valid()?Django
form = MyModelForm(data={'name': ''})
valid = form.is_valid()
errors = form.errorsAttempts:
2 left
💡 Hint
What does Django do when a required field is empty?
✗ Incorrect
Django adds an error message for each field that fails validation. Required fields missing data produce a 'This field is required.' error.
🧠 Conceptual
expert3:00remaining
How does Django ModelForm handle related model fields by default?
When a Django ModelForm is generated for a model with a ForeignKey field, how is that field represented in the form by default?
Attempts:
2 left
💡 Hint
Think about how Django lets users pick related objects in forms.
✗ Incorrect
Django renders ForeignKey fields as dropdown selects by default, showing choices from the related model.