Skip to content

Commit

Permalink
[1.11.x] Fixed #31073 -- Prevented CheckboxInput.get_context() from m…
Browse files Browse the repository at this point in the history
…utating attrs.

Backport of 02eff7e from master.
  • Loading branch information
PeteAndersen authored and felixxm committed Dec 11, 2019
1 parent 4f15016 commit e8fdf00
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
2 changes: 2 additions & 0 deletions django/forms/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,8 @@ def get_context(self, name, value, attrs):
if self.check_test(value):
if attrs is None:
attrs = {}
else:
attrs = attrs.copy()
attrs['checked'] = True
return super(CheckboxInput, self).get_context(name, value, attrs)

Expand Down
5 changes: 5 additions & 0 deletions tests/forms_tests/widget_tests/test_checkboxinput.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,8 @@ def test_value_from_datadict_string_int(self):
def test_value_omitted_from_data(self):
self.assertIs(self.widget.value_omitted_from_data({'field': 'value'}, {}, 'field'), False)
self.assertIs(self.widget.value_omitted_from_data({}, {}, 'field'), False)

def test_get_context_does_not_mutate_attrs(self):
attrs = {'checked': False}
self.widget.get_context('name', True, attrs)
self.assertIs(attrs['checked'], False)
11 changes: 11 additions & 0 deletions tests/postgres_tests/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,17 @@ def test_get_context(self):
}
)

def test_checkbox_get_context_attrs(self):
context = SplitArrayWidget(
forms.CheckboxInput(),
size=2,
).get_context('name', [True, False])
self.assertEqual(context['widget']['value'], '[True, False]')
self.assertEqual(
[subwidget['attrs'] for subwidget in context['widget']['subwidgets']],
[{'checked': True}, {}]
)

def test_render(self):
self.check_html(
SplitArrayWidget(forms.TextInput(), size=2), 'array', None,
Expand Down

0 comments on commit e8fdf00

Please sign in to comment.