from django.utils.translation import ugettext_lazy as _
from django_choices_enum.enums import ChoiceEnum
class ColorEnum(ChoiceEnum):
RED = _('Red')
BLUE = _('Blue')
GREEN = _('Green')
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .enums import ColorEnum
class ColorPalette(models.Model):
color = models.CharField(_('Color'), max_length=30, choices=ColorEnum)
ColorPalette.objects.filter(color=ColorEnum.RED)
View:
def my_page(request):
context = {
'ColorEnum': ColorEnum,
'color_palette': ColorPalette.objects.filter(color=ColorEnum.BLUE).first(),
}
return render(request, 'my_app/index.html', context)
Template:
<p>The color is {% if color_palette.color == ColorEnum.BLUE %}blue{% else %}not blue{% endif %}</p>
Will result in:
<p>The color is blue</p>
In [1]: ColorEnum.GREEN == 'GREEN'
Out[1]: True
In [1]: ColorEnum.RED.label
Out[1]: 'Red'
from django.utils.translation import ugettext_lazy as _
from django_choices_enum.enums import IntChoiceEnum
class ShakeEnum(IntChoiceEnum):
CHOCO = 1
VANILLA = 2
MINT = 3
__choices_label_map__ = {
CHOCO: _('Chocolatey'),
VANILLA: _('Vanilla'),
MINT: _('Minty'),
}
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .enums import ShakeEnum
class Smoothie(models.Model):
shake = models.SmallIntegerField(_('Shake'), choices=ShakeEnum)
Smoothie.objects.filter(shake=ShakeEnum.VANILLA)
View:
def my_page(request):
context = {
'ShakeEnum': ShakeEnum,
'smoothie': Smoothie.objects.filter(shake=ShakeEnum.MINT).first(),
}
return render(request, 'my_app/index.html', context)
Template:
<p>Your shake contains {% if smoothie.shake == ShakeEnum.MINT %}fresh mint{% else %}something not minty{% endif %}</p>
Will result in:
<p>Your shake contains fresh mint</p>
In [1]: ShakeEnum.MINT == 3
Out[1]: True
In [1]: ShakeEnum.MINT.label
Out[1]: 'Minty'