From 8caf524a1dd35d57827dff6950460f9d8b9d2dab Mon Sep 17 00:00:00 2001 From: Claude Paroz Date: Sat, 17 Oct 2020 16:17:00 +0200 Subject: [PATCH] [3.1.x] Fixed #32110 -- Doc'd and tested enumerations for ChoiceField.choices. Backport of 7f85498eef1d8fcc52e4fb70df8041f5452d405a from master --- docs/ref/forms/fields.txt | 13 +++++++------ tests/forms_tests/field_tests/test_choicefield.py | 12 ++++++++++++ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/docs/ref/forms/fields.txt b/docs/ref/forms/fields.txt index 0bcf07ff08a..44ccdbf7650 100644 --- a/docs/ref/forms/fields.txt +++ b/docs/ref/forms/fields.txt @@ -410,12 +410,13 @@ For each field, we describe the default widget used if you don't specify .. attribute:: choices Either an :term:`iterable` of 2-tuples to use as choices for this - field, or a callable that returns such an iterable. This argument - accepts the same formats as the ``choices`` argument to a model field. - See the :ref:`model field reference documentation on choices - ` for more details. If the argument is a callable, it is - evaluated each time the field's form is initialized, in addition to - during rendering. Defaults to an empty list. + field, :ref:`enumeration ` choices, or a + callable that returns such an iterable. This argument accepts the same + formats as the ``choices`` argument to a model field. See the + :ref:`model field reference documentation on choices ` + for more details. If the argument is a callable, it is evaluated each + time the field's form is initialized, in addition to during rendering. + Defaults to an empty list. ``TypedChoiceField`` -------------------- diff --git a/tests/forms_tests/field_tests/test_choicefield.py b/tests/forms_tests/field_tests/test_choicefield.py index cdb264b36cf..f25e2cedfd8 100644 --- a/tests/forms_tests/field_tests/test_choicefield.py +++ b/tests/forms_tests/field_tests/test_choicefield.py @@ -1,4 +1,5 @@ from django.core.exceptions import ValidationError +from django.db import models from django.forms import ChoiceField, Form from django.test import SimpleTestCase @@ -87,3 +88,14 @@ class ChoiceFieldTest(FormFieldAssertionsMixin, SimpleTestCase): '' ) + + def test_choicefield_enumeration(self): + class FirstNames(models.TextChoices): + JOHN = 'J', 'John' + PAUL = 'P', 'Paul' + + f = ChoiceField(choices=FirstNames.choices) + self.assertEqual(f.clean('J'), 'J') + msg = "'Select a valid choice. 3 is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('3')