Opened 4 years ago

Closed 4 years ago

#31143 closed Uncategorized (wontfix)

Variable attribute resolution priority in templates.

Reported by: Vasili Korol Owned by: nobody
Component: Template system Version: dev
Severity: Normal Keywords: template, variable resolving
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Assume a Django model defining a __getitem__ method:

class DataBlob ( models.Model ) :

    # ... field & method definitions ...

    def get ( self, key ) :
         """Returns a value by key from a msgpacked structure stored in a file.
         """
         # ....

    def __getitem__ ( self, key ) :
        """Just a convenience shortcut for a method DataBlob.get.
        """
        return self.get( key )

Now, we would like to access the id of a DataBlob instance in a template:

<input type="hidden" id="VAL_datablob_id" value="{{datablob.id}}">

Expected result in the value property of the <input>: The id of the object.
Observed: The result of calling datablob['id'].

The logic in django.template.base.Variable._resolve_lookup is to first attempt a dictinary lookup, and then fallback to attribute lookup.

Why is it prioritized this way? In the current implementation, the "dictionary-interpreted" keys will take precedence over object attributes, masking them completely if the names are the same. I think it is more logical to give priority to the attributes.

(I selected version 1.11 for this ticket, but i think it's the same for 2.2 and 3.0).

Change History (1)

comment:1 by Mariusz Felisiak, 4 years ago

Resolution: wontfix
Status: newclosed
Summary: Variable attribute resolution priority in templatesVariable attribute resolution priority in templates.
Version: 1.11master

This decision was made at the very beginning and it's documented since 2005 (see 096ad32c845f850278b942d087e607dc4311b5f9). If you need a different behavior you can always create a custom template filter.

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