From 26f8929f16c514bd9967cd78d8dcd7760b82cc92 Mon Sep 17 00:00:00 2001 From: afenoum Date: Sun, 15 Mar 2026 14:18:59 +0300 Subject: Fixed #36913 -- Optimized MultipleChoiceField.validate(). --- AUTHORS | 1 + django/forms/fields.py | 3 ++- .../forms_tests/field_tests/test_multiplechoicefield.py | 17 +++++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/AUTHORS b/AUTHORS index 9379176a4c..bea9d3fd4d 100644 --- a/AUTHORS +++ b/AUTHORS @@ -35,6 +35,7 @@ answer newbie questions, and generally made Django that much better: Ahmad Al-Ibrahim Ahmed Eltawela Ahmed Nassar + Aina Anjary Fenomamy R. ajs Akash Agrawal Akash Kumar Sen diff --git a/django/forms/fields.py b/django/forms/fields.py index 6408be2f06..7f978aa03d 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -965,7 +965,8 @@ class MultipleChoiceField(ChoiceField): if self.required and not value: raise ValidationError(self.error_messages["required"], code="required") # Validate that each value in the value list is in self.choices. - for val in value: + # Use set() to avoid redundant validation. + for val in set(value): if not self.valid_value(val): raise ValidationError( self.error_messages["invalid_choice"], diff --git a/tests/forms_tests/field_tests/test_multiplechoicefield.py b/tests/forms_tests/field_tests/test_multiplechoicefield.py index f316e1de8e..90a47ceee0 100644 --- a/tests/forms_tests/field_tests/test_multiplechoicefield.py +++ b/tests/forms_tests/field_tests/test_multiplechoicefield.py @@ -76,3 +76,20 @@ class MultipleChoiceFieldTest(SimpleTestCase): def test_disabled_has_changed(self): f = MultipleChoiceField(choices=[("1", "One"), ("2", "Two")], disabled=True) self.assertIs(f.has_changed("x", "y"), False) + + def test_validate_duplicated_values(self): + f = MultipleChoiceField( + choices=[ + ("1", "One"), + ("2", "Two"), + ("3", "Three"), + ("4", "Four"), + ("5", "Five"), + ] + ) + self.assertIsNone(f.validate(["4", "4", "5", "5"])) + + def test_validate_duplicated_invalid_values(self): + f = MultipleChoiceField(choices=[("1", "one"), ("2", "Two")]) + with self.assertRaises(ValidationError): + f.validate(["1", "1", "invalid", "invalid"]) -- cgit v1.3