Created
April 9, 2018 23:49
-
-
Save treyhunner/fd2dc64efb50a147e0a29746862fe8fc to your computer and use it in GitHub Desktop.
Enum for use with Django ChoiceField
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from enum import Enum, EnumMeta | |
class ChoiceEnumMeta(EnumMeta): | |
def __iter__(self): | |
return ((tag, tag.value) for tag in super().__iter__()) | |
class ChoiceEnum(Enum, metaclass=ChoiceEnumMeta): | |
""" | |
Enum for Django ChoiceField use. | |
Usage:: | |
class Colors(ChoiceEnum): | |
red = "Red" | |
green = "Green" | |
blue = "Blue" | |
class MyModel(models.Model): | |
color = models.CharField(max_length=20, choices=Colors) | |
""" |
def choices(em):
return [(e.value, e.name) for e in em]
class Color(IntEnum):
red = 0
green = 1
blue = 2
color = models.IntegerField(max_length=20, choices=choices(Color))
I would like to use this
django-model-utils
https://github.com/jazzband/django-model-utils/blob/master/docs/utilities.rst
from model_utils import Choices
class Article(models.Model):
STATUS = Choices('draft', 'published')
status = models.CharField(choices=STATUS, default=STATUS.draft, max_length=20)
@waketzheng, you're the man! thanks for pointing to django-model-utils
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It "compiles" but I'm getting the following error in Django admin, when I go to edit an object: