diff options
| author | afenoum <anja1catus@gmail.com> | 2026-03-15 14:18:59 +0300 |
|---|---|---|
| committer | Jacob Walls <jacobtylerwalls@gmail.com> | 2026-03-25 09:23:10 -0400 |
| commit | 26f8929f16c514bd9967cd78d8dcd7760b82cc92 (patch) | |
| tree | 2a0cb990a4132967197087f23430cab2ce91bb3c | |
| parent | 386257b33eb2a925cecc1a12ba5e7dd694617186 (diff) | |
Fixed #36913 -- Optimized MultipleChoiceField.validate().
| -rw-r--r-- | AUTHORS | 1 | ||||
| -rw-r--r-- | django/forms/fields.py | 3 | ||||
| -rw-r--r-- | tests/forms_tests/field_tests/test_multiplechoicefield.py | 17 |
3 files changed, 20 insertions, 1 deletions
@@ -35,6 +35,7 @@ answer newbie questions, and generally made Django that much better: Ahmad Al-Ibrahim Ahmed Eltawela <https://github.com/ahmedabt> Ahmed Nassar <https://ahmednassar7.github.io/> + Aina Anjary Fenomamy R. <anja1catus@gmail.com> ajs <adi@sieker.info> Akash Agrawal <akashrocksha@gmail.com> Akash Kumar Sen <akashkumarsen4@gmail.com> 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"]) |
