Opened 6 years ago

Closed 6 years ago

#29306 closed Bug (duplicate)

Prevent template variable lookups from intiatiating a class

Reported by: Luoxzhg Owned by: Luoxzhg
Component: Template system Version: dev
Severity: Normal Keywords: template
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Luoxzhg)

class A:
    def __init__(self, value): 
         pass
    attr="Hello"

from django.template import Template, Context
t = Template(" {{  A.attr }}")
output=t.render(Context({"A": A}))

the output should be "Hello", but it is string_if_invalid, i.e., empty string "" .

Change History (5)

comment:1 by Luoxzhg, 6 years ago

Description: modified (diff)
Summary: [bugs for all version]Template variable-lookups system evaluate callables before completed the evaluation[bugs]Template variable-lookups system invoke class when access class attribute

comment:2 by Luoxzhg, 6 years ago

Owner: changed from nobody to Luoxzhg
Status: newassigned

comment:3 by Tim Graham, 6 years ago

Easy pickings: unset
Summary: [bugs]Template variable-lookups system invoke class when access class attributePrevent template variable lookups from intiatiating a class
Triage Stage: UnreviewedAccepted

comment:4 by Tim Graham, 6 years ago

I understand the desire for the behavior change, however, the change could be backwards incompatible. Consider this case which will pass before the change but fail afterward:

@setup({'t': '{{ A.attr }}'})
def test_class_attribute(self):
    """Accessing an attribute of an instantiated class."""
    class A:

        def __init__(self):
            self.attr = 'Hello'

    self.assertEqual(self.engine.render_to_string('t', {'A': A}), 'Hello')

Is there any documentation to suggest the current behavior is incorrect?

comment:5 by Carlton Gibson, 6 years ago

Resolution: duplicate
Status: assignedclosed

I think this is expected behaviour, that has a workaround.

#15791 added a check for a do_not_call_in_templates attribute on a callable.

Setting this to True in the example test case allows it to pass.

This is documented in the Variables and lookups section of the Template API docs.

Closing as a duplicate of #15791

Note: See TracTickets for help on using tickets.
Back to Top