How to access Enum types in Django templates

I had a problem, wherever I do, I could not access IntEnum (from enum34 lib) in my Django template.

I managed to get around it by translating it into 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

They do not work when DEMO is IntEnum, but when DEMO is converted to 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?

+4
source share
2 answers

A little more digging, and I found the answer.

From website :

Technically, when the template system encounters a point, it tries to perform the following searches in the following order:

Search dictionary

Search for attribute or method

Numeric Index Search

, . .

:

/ ,...

:

  • lookup 'DEMOS' context, <enum 'DEMOS'>

  • , ()

  • TypeError

, , Enum , , ( : '').

, . django.templates.base :

if getattr(current, 'do_not_call_in_templates', False):
    pass

do_not_call_in_templates, True, , .

Python Enum ( enum34 backport), . Django , :

def forDjango(cls):
    cls.do_not_call_in_templates = True
    return cls

Enum:

@forDjango
class DEMOS(Enum):
    eggs = 'runny'
    spam = 'hard'
    cheese = 'smelly'

Enum, Enums .

+5

Django Enum, __members__:

context['DEMOS'] = DEMOS.__members__

0

All Articles