Created
September 19, 2018 13:50
-
-
Save mgd020/518fff37a7fa937a81e569b3e3a54801 to your computer and use it in GitHub Desktop.
nice choices class for
This file contains 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
""" | |
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