How to access Enum types in Django templates

Viewed 10104

I was having an issue where no matter what I did I couldn't access an IntEnum (from the enum34 lib) in my Django template.

I was able to get around it by converting it to a dict:

def get_context_data(self, **kwargs):
    context = super(MyView, self).get_context_data(**kwargs)
    # Django templates don't play nice with Enums
    context['DEMOS'] = {d.name: d for d in DEMOS}
    # `context['DEMOS'] = DEMOS` doesn't work
    return context

These don't work when DEMO is an IntEnum, but do when DEMO is converted to a dict:

{{ DEMO.FOO }}  # outputs nothing
{{ DEMO.FOO|default_if_none:'foo' }}  # outputs nothing
{{ DEMO.FOO.value }}  # outputs nothing
{% if DEMO.FOO == 1 %}  # no matter what I compare to, always False

Any ideas why? Is this a known issue?

2 Answers
Related