1
0
mirror of https://github.com/django/django.git synced 2025-10-24 14:16:09 +00:00

Fixed #27910 -- Added enumeration helpers for use in Field.choices.

These classes can serve as a base class for user enums, supporting
translatable human-readable names, or names automatically inferred
from the enum member name.

Additional properties make it easy to access the list of names, values
and display labels.

Thanks to the following for ideas and reviews:

Carlton Gibson, Fran Hrženjak, Ian Foote, Mariusz Felisiak, Shai Berger.

Co-authored-by: Shai Berger <shai@platonix.com>
Co-authored-by: Nick Pope <nick.pope@flightdataservices.com>
Co-authored-by: Mariusz Felisiak <felisiak.mariusz@gmail.com>
This commit is contained in:
Shai Berger
2018-12-31 19:57:35 +02:00
committed by Mariusz Felisiak
parent 25706d7285
commit 72ebe85a26
11 changed files with 554 additions and 4 deletions

View File

@@ -184,6 +184,9 @@ class PositiveIntegerFieldTests(IntegerFieldTests):
class ValidationTests(SimpleTestCase):
class Choices(models.IntegerChoices):
A = 1
def test_integerfield_cleans_valid_string(self):
f = models.IntegerField()
self.assertEqual(f.clean('2', None), 2)
@@ -217,3 +220,14 @@ class ValidationTests(SimpleTestCase):
f = models.IntegerField(choices=((1, 1),))
with self.assertRaises(ValidationError):
f.clean('0', None)
def test_enum_choices_cleans_valid_string(self):
f = models.IntegerField(choices=self.Choices.choices)
self.assertEqual(f.clean('1', None), 1)
def test_enum_choices_invalid_input(self):
f = models.IntegerField(choices=self.Choices.choices)
with self.assertRaises(ValidationError):
f.clean('A', None)
with self.assertRaises(ValidationError):
f.clean('3', None)