Opened 14 months ago
Last modified 14 months ago
#35735 closed Bug
For python 3.9+ class property may not be accessible by Django's template system — at Version 2
| Reported by: | Fabian Braun | Owned by: | Fabian Braun |
|---|---|---|---|
| Component: | Template system | Version: | dev |
| Severity: | Normal | Keywords: | |
| Cc: | Fabian Braun | Triage Stage: | Ready for checkin |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description (last modified by )
Before python 3.9 class properties were always available through the template system. If you had a class
class MyClass:
in_template = True
you could access the class property in the template through (if it was returned by a callable) {{ get_my_class.in_template }}.
The template system first checks if the class is subscriptable (i.e. tries context_value["in_template"]), will fail and then will get the in_template property.
As of python 3.9 some classes actually are subscriptable and trying to get the item will not fail: Typing shortcuts introduced syntax like list[int]. This hides class properties from the template system.
Here's a test (that might go into tests/template_tests/syntax_tests/tests_basic.py) which passes on Python 3.9 and fails on Python 3.10+:
@setup({"basic-syntax19b": "{{ klass.in_template }}"})
def test_access_class_property(self):
class MyClass(list):
in_template = True
def get_my_class():
return MyClass
# Pass the callable to return the class, or it would be resolved by the template
# engine
output = self.engine.render_to_string(
"basic-syntax19b",
{"klass": get_my_class}
)
self.assertEqual(output, "True")
I'd be happy to propose a fix that will not call a classes' __class_getitem__ method.
Thanks to Ben Stähli and Serhii Tereshchenko for figuring out this issue.
References:
Change History (2)
comment:1 by , 14 months ago
| Description: | modified (diff) |
|---|---|
| Owner: | set to |
| Status: | new → assigned |
comment:2 by , 14 months ago
| Description: | modified (diff) |
|---|---|
| Summary: | For python 3.10+ class property may not be accessible by Django's template system → For python 3.9+ class property may not be accessible by Django's template system |
| Type: | Uncategorized → Bug |