Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Enum for use with Django ChoiceField
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)
"""
@nitrag

This comment has been minimized.

Copy link

@nitrag nitrag commented Jun 17, 2018

It "compiles" but I'm getting the following error in Django admin, when I go to edit an object:

  File "/Users/ryan/Documents/asdf/django/lib/python3.6/site-packages/django/forms/widgets.py", line 677, in get_context
    context = super().get_context(name, value, attrs)
  File "/Users/ryan/Documents/asdf/django/lib/python3.6/site-packages/django/forms/widgets.py", line 637, in get_context
    context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs)
  File "/Users/ryan/Documents/asdf/django/lib/python3.6/site-packages/django/forms/widgets.py", line 585, in optgroups
    for index, (option_value, option_label) in enumerate(self.choices):
  File "/Users/ryan/Documents/asdf/django/lib/python3.6/site-packages/django/forms/fields.py", line 747, in __iter__
    yield from self.choices_func()
TypeError: __call__() missing 1 required positional argument: 'value'
@yifeikong

This comment has been minimized.

Copy link

@yifeikong yifeikong commented Jul 7, 2018

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

@waketzheng

This comment has been minimized.

Copy link

@waketzheng waketzheng commented Jul 25, 2018

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)
@freemansion

This comment has been minimized.

Copy link

@freemansion freemansion commented Jul 30, 2018

@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