Bird
Raised Fist0
Djangoframework~20 mins

Formsets for multiple 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
🎖️
Formset Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Django formset rendering?
Given this Django formset code snippet, what HTML output will be generated for the management form part?
Django
from django import forms
from django.forms import formset_factory

class ItemForm(forms.Form):
    name = forms.CharField(max_length=100)

ItemFormSet = formset_factory(ItemForm, extra=2)

formset = ItemFormSet()

print(formset.management_form.as_p())
A<p><input type="hidden" name="form-TOTAL_FORMS" value="1" id="id_form-TOTAL_FORMS" /></p><p><input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS" /></p>
B<p><input type="hidden" name="form-TOTAL_FORMS" value="0" id="id_form-TOTAL_FORMS" /></p><p><input type="hidden" name="form-INITIAL_FORMS" value="2" id="id_form-INITIAL_FORMS" /></p>
C<p><input type="hidden" name="form-TOTAL_FORMS" value="2" id="id_form-TOTAL_FORMS" /></p><p><input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS" /></p><p><input type="hidden" name="form-MIN_NUM_FORMS" value="0" id="id_form-MIN_NUM_FORMS" /></p><p><input type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS" /></p>
D<p><input type="hidden" name="form-TOTAL_FORMS" value="2" id="id_form-TOTAL_FORMS" /></p><p><input type="hidden" name="form-INITIAL_FORMS" value="2" id="id_form-INITIAL_FORMS" /></p>
Attempts:
2 left
💡 Hint
Remember that extra=2 means two empty forms are created, so TOTAL_FORMS is 2 and INITIAL_FORMS is 0.
state_output
intermediate
2:00remaining
What is the value of cleaned_data after validating this formset?
Consider this Django formset with two forms submitted with data. What will be the cleaned_data list after calling is_valid()?
Django
from django import forms
from django.forms import formset_factory

class ProductForm(forms.Form):
    product_name = forms.CharField(max_length=50)
    quantity = forms.IntegerField(min_value=1)

ProductFormSet = formset_factory(ProductForm, extra=0)

form_data = {
    'form-TOTAL_FORMS': '2',
    'form-INITIAL_FORMS': '0',
    'form-MIN_NUM_FORMS': '0',
    'form-MAX_NUM_FORMS': '1000',
    'form-0-product_name': 'Apples',
    'form-0-quantity': '5',
    'form-1-product_name': 'Bananas',
    'form-1-quantity': '0'
}

formset = ProductFormSet(form_data)
valid = formset.is_valid()
cleaned = formset.cleaned_data if valid else None
print(cleaned)
A[{'product_name': 'Apples', 'quantity': 5}, {'product_name': 'Bananas', 'quantity': 0}]
B[{'product_name': 'Apples', 'quantity': 5}, {'product_name': 'Bananas', 'quantity': 1}]
C[{'product_name': 'Apples', 'quantity': 5}]
Dnull
Attempts:
2 left
💡 Hint
Check the quantity field validation for the second form.
📝 Syntax
advanced
2:00remaining
Which option correctly creates two different formsets for two models in one view?
You want to create formsets for two different Django models, Author and Book, in the same view. Which code snippet correctly defines and initializes both formsets?
Django
from django.forms import modelformset_factory
from myapp.models import Author, Book

AuthorFormSet = modelformset_factory(Author, fields=('name',), extra=1)
BookFormSet = modelformset_factory(Book, fields=('title',), extra=1)

# Initialize formsets with POST data
if request.method == 'POST':
    author_formset = AuthorFormSet(request.POST, prefix='authors')
    book_formset = BookFormSet(request.POST, prefix='books')
A
author_formset = AuthorFormSet(request.POST)
book_formset = BookFormSet(request.POST)
B
author_formset = AuthorFormSet(request.POST, prefix='authors')
book_formset = BookFormSet(request.POST, prefix='books')
C
author_formset = AuthorFormSet(prefix='authors')
book_formset = BookFormSet(prefix='books')
D
author_formset = AuthorFormSet(request.POST, prefix='books')
book_formset = BookFormSet(request.POST, prefix='authors')
Attempts:
2 left
💡 Hint
When using multiple formsets in one view, each must have a unique prefix.
🔧 Debug
advanced
2:00remaining
Why does this formset always show zero forms despite extra=3?
This code tries to create a formset with 3 extra forms but the rendered formset shows no forms. What is the cause?
Django
from django import forms
from django.forms import formset_factory

class TaskForm(forms.Form):
    task = forms.CharField(max_length=100)

TaskFormSet = formset_factory(TaskForm, extra=3)

formset = TaskFormSet(data=None)

print(len(formset.forms))
ABecause data=null is passed, the formset treats it as bound with no data and shows zero forms.
BBecause extra=3 is ignored when data is null; it only applies when initial data is provided.
CBecause the formset is unbound, it should show 3 forms; the issue is elsewhere.
DBecause the formset requires initial data to show forms, extra=3 has no effect without initial.
Attempts:
2 left
💡 Hint
Check how passing data=null affects formset binding and form count.
🧠 Conceptual
expert
2:00remaining
How does prefix affect multiple formsets in one Django template?
You have two formsets in one template: author_formset with prefix 'authors' and book_formset with prefix 'books'. What is the main reason to use prefixes here?
APrefixes prevent form field name collisions so Django can distinguish which data belongs to which formset on POST.
BPrefixes automatically validate the forms without needing is_valid() calls.
CPrefixes change the formset layout in the template to group forms visually.
DPrefixes allow formsets to share the same management form without conflicts.
Attempts:
2 left
💡 Hint
Think about how HTML form input names are sent in POST requests.

Practice

(1/5)
1. What is the main purpose of using a formset in Django?
easy
A. To create a single form with multiple fields
B. To manage multiple similar forms together easily
C. To handle file uploads in a form
D. To validate a single form's data

Solution

  1. Step 1: Understand what formsets do

    A formset groups many similar forms so you can handle them together.
  2. Step 2: Compare options

    The other options describe single form tasks, not multiple forms management.
  3. Final Answer:

    To manage multiple similar forms together easily -> Option B
  4. Quick Check:

    Formsets = multiple forms management [OK]
Hint: Formsets group many forms, not just one [OK]
Common Mistakes:
  • Thinking formsets are for single forms
  • Confusing formsets with file upload handling
  • Assuming formsets validate only one form
2. Which function is used to create a formset for regular Django forms?
easy
A. formset_factory
B. form_factory
C. create_formset
D. modelformset_factory

Solution

  1. Step 1: Recall Django formset functions

    Django uses formset_factory for regular forms and modelformset_factory for model forms.
  2. Step 2: Match options to correct function

    Only formset_factory matches the function for regular forms.
  3. Final Answer:

    formset_factory -> Option A
  4. Quick Check:

    Regular forms use formset_factory [OK]
Hint: Remember: model forms use modelformset_factory, others use formset_factory [OK]
Common Mistakes:
  • Confusing modelformset_factory with formset_factory
  • Using non-existent functions like create_formset
  • Mixing up form_factory with formset_factory
3. Given this code snippet, what will formset.is_valid() check for?
MyFormSet = formset_factory(MyForm, extra=2)
formset = MyFormSet(request.POST)
valid = formset.is_valid()
medium
A. It always returns True because extra forms are empty
B. It checks only the first form in the formset
C. It checks if all forms in the formset have valid data
D. It raises an error because management form is missing

Solution

  1. Step 1: Understand formset.is_valid()

    This method validates every form in the formset, including extra forms if data is submitted.
  2. Step 2: Consider management form presence

    Since request.POST is passed, management form data is expected and included, so no error.
  3. Final Answer:

    It checks if all forms in the formset have valid data -> Option C
  4. Quick Check:

    formset.is_valid() = all forms valid [OK]
Hint: is_valid checks all forms, not just one [OK]
Common Mistakes:
  • Assuming only first form is validated
  • Thinking extra empty forms cause always True
  • Ignoring management form data requirement
4. What is the common cause of a ManagementForm data is missing or has been tampered with error when using formsets?
medium
A. Setting extra=0 in the formset factory
B. Using modelformset_factory instead of formset_factory
C. Calling formset.is_valid() before binding data
D. Not including the management form in the HTML template

Solution

  1. Step 1: Identify management form role

    The management form holds hidden fields needed to track formset data like total forms count.
  2. Step 2: Understand error cause

    If the management form is missing in the HTML, Django cannot verify formset data, causing this error.
  3. Final Answer:

    Not including the management form in the HTML template -> Option D
  4. Quick Check:

    Missing management form = error [OK]
Hint: Always include {{ formset.management_form }} in templates [OK]
Common Mistakes:
  • Confusing factory functions with management form errors
  • Thinking extra=0 causes this error
  • Calling is_valid without data binding causes different errors
5. You want to create a formset to edit multiple instances of a model Book. Which approach correctly creates and processes this formset in a view?
hard
A. Use modelformset_factory(Book), instantiate with request.POST, validate, then save if valid
B. Use formset_factory(BookForm), instantiate with request.GET, then save without validation
C. Use modelformset_factory(Book), instantiate without data, then call save() directly
D. Use formset_factory(BookForm), instantiate with request.POST, but skip management form

Solution

  1. Step 1: Choose correct factory for model instances

    To edit model instances, use modelformset_factory with the model Book.
  2. Step 2: Instantiate with POST data and validate

    Pass request.POST to bind submitted data, call is_valid(), then save if valid.
  3. Step 3: Avoid skipping management form or using GET

    Management form is required; GET is not for submitting form data.
  4. Final Answer:

    Use modelformset_factory(Book), instantiate with request.POST, validate, then save if valid -> Option A
  5. Quick Check:

    Model formset + POST + validate + save = correct [OK]
Hint: Model instances need modelformset_factory and POST data [OK]
Common Mistakes:
  • Using formset_factory for model instances
  • Skipping validation before saving
  • Using GET instead of POST for form submission
  • Omitting management form in template