Bird
Raised Fist0
Djangoframework~20 mins

ModelForm for model-backed forms in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
ModelForm Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2: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?
AThe object is created but not saved to the database yet.
BThe object is saved to the database immediately.
CThe object is not created at all until commit=True is used.
DThe object is deleted from the database.
Attempts:
2 left
💡 Hint
Think about what commit=False means in Django ModelForm save method.
📝 Syntax
intermediate
2: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'
Aexclude = ['created_at']
Bfields = ['created_at']
Cexclude = 'created_at'
Dfields = '__all__' except 'created_at'
Attempts:
2 left
💡 Hint
The exclude attribute expects a list of field names.
🔧 Debug
advanced
3: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()
AThe form is not valid because 'name' is missing.
BThe form.save() method is called without commit=False, causing a database error.
CThe 'email' field is required by the model but missing in the data, causing save to fail.
DThe ModelForm must include all model fields in fields list.
Attempts:
2 left
💡 Hint
Check which fields are required by the model and which are provided in the form data.
state_output
advanced
2: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.errors
A{}
B{'name': ['This field is required.']}
CNone
D{'non_field_errors': ['Invalid data']}
Attempts:
2 left
💡 Hint
What does Django do when a required field is empty?
🧠 Conceptual
expert
3: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?
AIt is excluded from the form automatically.
BAs a text input field expecting the related model's primary key.
CAs a hidden input field with the related model's ID.
DAs a dropdown select field listing related model instances.
Attempts:
2 left
💡 Hint
Think about how Django lets users pick related objects in forms.

Practice

(1/5)
1. What is the main purpose of using a ModelForm in Django?
easy
A. To handle user authentication
B. To write SQL queries manually
C. To style HTML forms with CSS
D. To create a form automatically linked to a database model

Solution

  1. Step 1: Understand what ModelForm does

    A ModelForm automatically creates a form based on a Django model, linking form fields to model fields.
  2. Step 2: Compare options with ModelForm purpose

    Only To create a form automatically linked to a database model describes this purpose correctly; others describe unrelated tasks.
  3. Final Answer:

    To create a form automatically linked to a database model -> Option D
  4. Quick Check:

    ModelForm = linked form to model [OK]
Hint: ModelForm links forms to models automatically [OK]
Common Mistakes:
  • Thinking ModelForm is for styling forms
  • Confusing ModelForm with SQL query writing
  • Assuming ModelForm handles authentication
2. Which of the following is the correct way to specify the model and fields in a Django ModelForm?
easy
A. class Meta: model = MyModel; fields = ['name', 'age']
B. class Meta: model MyModel fields ['name', 'age']
C. class Meta: model = MyModel fields = ('name', 'age')
D. class Meta: model = MyModel; fields = 'name, age'

Solution

  1. Step 1: Recall correct Meta syntax

    The Meta class must assign model and fields with equal signs and proper list syntax.
  2. Step 2: Check each option for syntax errors

    class Meta: model = MyModel; fields = ['name', 'age'] uses correct syntax with equal signs and list brackets. Others miss equal signs or use wrong types.
  3. Final Answer:

    class Meta: model = MyModel; fields = ['name', 'age'] -> Option A
  4. Quick Check:

    Meta uses = and list for fields [OK]
Hint: Use equal signs and list brackets in Meta class [OK]
Common Mistakes:
  • Omitting equal signs in Meta class
  • Using tuple instead of list for fields
  • Writing fields as a string instead of list
3. Given this model and form code:
class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ['title']

form = BookForm({'title': 'Django Basics', 'author': 'Alice'})
if form.is_valid():
    book = form.save()
    print(book.author)
else:
    print('Invalid form')

What will be printed?
medium
A. Alice
B. '' (empty string)
C. Django Basics
D. Error because author is missing

Solution

  1. Step 1: Understand fields included in the form

    The form only includes 'title' field, so 'author' is not set by the form.
  2. Step 2: Check what happens to author on save

    Since 'author' is not provided by the form, it remains empty (default empty string) on the saved model instance.
  3. Final Answer:

    '' (empty string) -> Option B
  4. Quick Check:

    Only 'title' saved, author empty [OK]
Hint: ModelForm saves only fields listed in Meta.fields [OK]
Common Mistakes:
  • Assuming all model fields are saved by ModelForm
  • Expecting form to validate missing fields not included
  • Thinking form data keys outside fields are saved
4. What is wrong with this ModelForm definition?
class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = 'name, age'
medium
A. fields should be a list or tuple, not a string
B. model should be a string, not a class
C. Meta class must be outside the form class
D. ModelForm cannot have fields attribute

Solution

  1. Step 1: Check the type of fields attribute

    fields must be a list or tuple of field names, not a single string.
  2. Step 2: Identify the error in the code

    Here, fields is a string 'name, age' which is incorrect syntax for fields.
  3. Final Answer:

    fields should be a list or tuple, not a string -> Option A
  4. Quick Check:

    fields = ['name', 'age'] not string [OK]
Hint: Use list or tuple for fields, not comma string [OK]
Common Mistakes:
  • Writing fields as a comma-separated string
  • Placing Meta class outside ModelForm
  • Using model as string instead of class
5. You want to create a ModelForm for a model Product with fields name, price, and stock. You want the form to include only name and price, but also want to add a custom validation that price must be positive. Which is the best way to do this?
hard
A. Create a ModelForm with all fields and override save() to check price
B. Create a regular Form with name and price fields and validate price manually
C. Create a ModelForm with Meta fields ['name', 'price'] and add a clean_price method to validate price > 0
D. Use ModelForm with Meta fields ['name', 'price', 'stock'] and ignore stock in the template

Solution

  1. Step 1: Select fields to include in ModelForm

    Use Meta class with fields = ['name', 'price'] to include only those fields.
  2. Step 2: Add custom validation for price

    Define a clean_price() method in the form to check price > 0 and raise ValidationError if not.
  3. Final Answer:

    Create a ModelForm with Meta fields ['name', 'price'] and add a clean_price method to validate price > 0 -> Option C
  4. Quick Check:

    Meta fields + clean_price() for validation [OK]
Hint: Use clean_fieldname() for custom field validation [OK]
Common Mistakes:
  • Validating in save() instead of clean methods
  • Including unwanted fields in Meta fields
  • Using regular Form instead of ModelForm unnecessarily