From f3b69f9757ec03057441ebbd52b7cdbfed31fb32 Mon Sep 17 00:00:00 2001 From: Claude Paroz Date: Fri, 30 Mar 2018 11:55:33 +0200 Subject: [PATCH] Fixed #29273 -- Prevented initial selection of empty choice in multiple choice widgets. Regression in b52c73008a9d67e9ddbb841872dc15cdd3d6ee01. --- django/forms/widgets.py | 2 ++ docs/releases/1.11.12.txt | 4 ++++ docs/releases/2.0.4.txt | 4 ++++ .../widget_tests/test_checkboxselectmultiple.py | 6 ++++-- tests/forms_tests/widget_tests/test_selectmultiple.py | 8 +++++--- 5 files changed, 19 insertions(+), 5 deletions(-) diff --git a/django/forms/widgets.py b/django/forms/widgets.py index 566bdf25d6..e4f8957189 100644 --- a/django/forms/widgets.py +++ b/django/forms/widgets.py @@ -649,6 +649,8 @@ class ChoiceWidget(Widget): def format_value(self, value): """Return selected values as a list.""" + if value is None and self.allow_multiple_selected: + return [] if not isinstance(value, (tuple, list)): value = [value] return [str(v) if v is not None else '' for v in value] diff --git a/docs/releases/1.11.12.txt b/docs/releases/1.11.12.txt index 64130c065e..186c18be58 100644 --- a/docs/releases/1.11.12.txt +++ b/docs/releases/1.11.12.txt @@ -12,3 +12,7 @@ Bugfixes * Fixed a regression in Django 1.11.8 where combining two annotated ``values_list()`` querysets with ``union()``, ``difference()``, or ``intersection()`` crashed due to mismatching columns (:ticket:`29229`). + +* Fixed a regression in Django 1.11 where an empty choice could be initially + selected for the ``SelectMultiple`` and ``CheckboxSelectMultiple`` widgets + (:ticket:`29273`) diff --git a/docs/releases/2.0.4.txt b/docs/releases/2.0.4.txt index d27ccf98bc..c0b51d257f 100644 --- a/docs/releases/2.0.4.txt +++ b/docs/releases/2.0.4.txt @@ -25,3 +25,7 @@ Bugfixes * Fixed a regression in Django 1.11.8 where combining two annotated ``values_list()`` querysets with ``union()``, ``difference()``, or ``intersection()`` crashed due to mismatching columns (:ticket:`29229`). + +* Fixed a regression in Django 1.11 where an empty choice could be initially + selected for the ``SelectMultiple`` and ``CheckboxSelectMultiple`` widgets + (:ticket:`29273`) diff --git a/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py b/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py index ef31ce9d36..07e5cca935 100644 --- a/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py +++ b/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py @@ -32,10 +32,12 @@ class CheckboxSelectMultipleTest(WidgetTest): def test_render_none(self): """ - If the value is None, none of the options are selected. + If the value is None, none of the options are selected, even if the + choices have an empty option. """ - self.check_html(self.widget(choices=self.beatles), 'beatles', None, html=( + self.check_html(self.widget(choices=(('', 'Unknown'),) + self.beatles), 'beatles', None, html=( """