Skip to content

Instantly share code, notes, and snippets.

@mgd020 mgd020/choices.py
Created Sep 19, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.