Skip to content

Commit

Permalink
[3.0.x] Fixed #31154 -- Added support for using enumeration types in …
Browse files Browse the repository at this point in the history
…templates.

Enumeration helpers are callables, so the template system tried to call
them with no arguments.

Thanks Rupert Baker for helping discover this.

Backport of 5166097 from master
  • Loading branch information
adamchainz authored and felixxm committed Jan 10, 2020
1 parent 2efc832 commit 16297e7
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 0 deletions.
1 change: 1 addition & 0 deletions django/db/models/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ def __new__(metacls, classname, bases, classdict):
# that is passed in as "self" as the value to use when looking up the
# label in the choices.
cls.label = property(lambda self: cls._value2label_map_.get(self.value))
cls.do_not_call_in_templates = True
return enum.unique(cls)

def __contains__(cls, member):
Expand Down
3 changes: 3 additions & 0 deletions docs/releases/3.0.3.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,6 @@ Bugfixes
* Relaxed the system check added in Django 3.0 to reallow use of a sublanguage
in the :setting:`LANGUAGE_CODE` setting, when a base language is available in
Django but the sublanguage is not (:ticket:`31141`).

* Added support for using enumeration types ``TextChoices``,
``IntegerChoices``, and ``Choices`` in templates (:ticket:`31154`).
6 changes: 6 additions & 0 deletions tests/model_enums/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import uuid

from django.db import models
from django.template import Context, Template
from django.test import SimpleTestCase
from django.utils.functional import Promise
from django.utils.translation import gettext_lazy as _
Expand Down Expand Up @@ -149,6 +150,11 @@ def test_str(self):
with self.subTest(member=member):
self.assertEqual(str(test[member.name]), str(member.value))

def test_templates(self):
template = Template('{{ Suit.DIAMOND.label }}|{{ Suit.DIAMOND.value }}')
output = template.render(Context({'Suit': Suit}))
self.assertEqual(output, 'Diamond|1')


class Separator(bytes, models.Choices):
FS = b'\x1c', 'File Separator'
Expand Down

0 comments on commit 16297e7

Please sign in to comment.