Opened 6 years ago

Closed 6 years ago

#21639 closed Bug (fixed)

RenderContext should override __getitem__

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

Description

From the comments for RenderContext:

Name resolution fails if a variable is not found at the top of the RequestContext stack. Thus, variables are local to a specific template and don't affect the rendering of other templates as they would if they were stored in the normal template context.


In RenderContext, the methods __iter__, get, and has_key are overridden. has_key is called internally by BaseContext.__contains__, so "in" works as expected, but get is not similarly called by __getitem__, so using get and using indexing syntax give different results. It seems to me that that's an oversight, and to be consistent with the intention as stated in the comment, __getitem__ should be overridden too.

Example of the wrong/inconsistent behaviour:

>>> from django.template.context import RenderContext
>>> c = RenderContext({'fruit': 'banana'})
>>> 'fruit' in c
True
>>> c.push()
{}
>>> 'fruit' in c
False
>>> c.get('fruit')
>>> c['fruit']
'banana'

Change History (4)

comment:2 Changed 6 years ago by Baptiste Mispelon

Needs tests: set
Patch needs improvement: set
Triage Stage: UnreviewedAccepted

Hi,

Indeed, this looks like an oversight and your patch looks reasonable.

Can you add some tests for it too?

Thanks.

comment:3 Changed 6 years ago by Alex Hill

Needs tests: unset

Of course, should have been in there to begin with. Done now, see the pull request.

Thanks for looking at this!

Alex

comment:4 Changed 6 years ago by Baptiste Mispelon <bmispelon@…>

Resolution: fixed
Status: newclosed

In 832ab0dbaacf381d15445259f292d88175ff84f2:

Fixed #21639 -- Implemented RenderContext.getitem

It's now consistent with RenderContext.get.

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