Skip to content

Instantly share code, notes, and snippets.

@mgd020
Created September 19, 2018 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgd020/518fff37a7fa937a81e569b3e3a54801 to your computer and use it in GitHub Desktop.
Save mgd020/518fff37a7fa937a81e569b3e3a54801 to your computer and use it in GitHub Desktop.
nice choices class for
"""
Example usage:
# declare
class Color(Choices):
RED = 'Red'
GREEN = 'Green'
BLUE = 'Blue'
# use on model
class Row(Model):
color = models.TextField(choices=Color, default=Color.RED)
# or on form
class RowForm(Form):
color = forms.ChoiceField(choices=Color)
"""
from enum import Enum, EnumMeta
class ChoicesMeta(EnumMeta):
def __iter__(self):
return ((tag.name, tag.value) for tag in super().__iter__())
def __call__(self, *args, **kwargs):
"""Create or lookup value.
If no arguments are passed (django.forms.ChoiceField), return iterator
to choices.
"""
if args or kwargs:
return super().__call__(*args, **kwargs)
return self.__iter__()
class Choices(Enum, metaclass=ChoicesMeta):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment