← All challenges
harddjango/django · v4.2

Rendering empty_form crashes when empty_permitted is passed to form_kwargs

Try this bug with AI

Fix it in the original repo with an AI agent and get feedback on how you worked.

2 free rounds each week

Round mode
  • Time limit60 min
  • Token budgetup to 1M
  • Worth up to310 XP
Sign up or sign in to start

Read the sample report

From a simulated Django round

You changed code before reproducing the bug.

Run the failing test before the first edit, so you know the failure you are fixing and can tell when it is gone.

Problem statement

Description

Issue
When explicitly setting form_kwargs = {'empty_permitted':True} or form_kwargs = {'empty_permitted':False} , a KeyError occurs when rendering a template that uses a formset's empty_form.
Expected Behavior
empty_permitted is ignored for formset.empty_form since empty_permitted is irrelevant for empty_form, as empty_form is not meant to be used to pass data and therefore does not need to be validated.
Steps to Reproduce

views.py

from django.shortcuts import render
from .models import MyModel
def test_view(request):
context = {}
ff = modelformset_factory(MyModel, fields = ['a_field'])
context['formset'] = ff(
queryset = MyModel.objects.none(),
form_kwargs = {'empty_permitted':True} # or form_kwargs = {'empty_permitted':False}
)
return render(request, 'my_app/my_model_formset.html', context)

urls.py

from django.urls import path, include
from .views import test_view
urlpatterns = [
path('test', test_view)
]

my_model_formset.html

{% extends "my_app/base.html" %}
{% block content %}
<form id="my-form" method="post">
{% csrf_token %}
{{ formset }}
<input type="submit" value="Save">
</form>
{{ formset.empty_form }}
{% endblock %}

The environment starts at commit 6df9398cce06 (django/django 4.2), dependencies installed and tests runnable from the first minute. You are graded by hidden tests taken from the fix that was actually merged upstream.