From bb94e1b7dbd42af51d805efafe52b22eb86d5ebe Mon Sep 17 00:00:00 2001 From: Laurens Verhoeven <12578054+laurensverhoeven@users.noreply.github.com> Date: Fri, 17 Feb 2023 21:05:00 +0100 Subject: [PATCH] [4.2.x] Fixed #34349 -- Fixed FormSet.empty_form crash when deleting extra forms is disabled. Backport of 6cbc403b8ee7014bd6dae4892d404eedb1d4a50d from main --- django/forms/formsets.py | 4 +++- tests/forms_tests/tests/test_formsets.py | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/django/forms/formsets.py b/django/forms/formsets.py index f14e1aae830..0fa832a2482 100644 --- a/django/forms/formsets.py +++ b/django/forms/formsets.py @@ -492,7 +492,9 @@ class BaseFormSet(RenderableFormMixin): required=False, widget=self.get_ordering_widget(), ) - if self.can_delete and (self.can_delete_extra or index < initial_form_count): + if self.can_delete and ( + self.can_delete_extra or (index is not None and index < initial_form_count) + ): form.fields[DELETION_FIELD_NAME] = BooleanField( label=_("Delete"), required=False, diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py index f0e4b154b7e..9e04b748f5f 100644 --- a/tests/forms_tests/tests/test_formsets.py +++ b/tests/forms_tests/tests/test_formsets.py @@ -1482,6 +1482,7 @@ class FormsFormsetTestCase(SimpleTestCase): self.assertIn("DELETE", formset.forms[0].fields) self.assertNotIn("DELETE", formset.forms[1].fields) self.assertNotIn("DELETE", formset.forms[2].fields) + self.assertNotIn("DELETE", formset.empty_form.fields) formset = ChoiceFormFormset( data={