1

I am setting

request.session['total_items'] = 3

in a views.py file of a django app

in template i got to know that you can access it as {{request.session.total_items}}

Everything is fine and i'm able to get the value.

However,my question is that why it is not {{request.session['total_items']}} instead, since request.session is a dictionary like object.

For {{request.session['total_items']}}, its giving an error as following:

Could not parse the remainder: '['total_items']' from 'request.session['total_items']'

Any help would be appreciated ...

4

2 回答 2

2

Do not confuse Django template language with Python Syntax. Django template language its a language on its own and have its own way of performing things. As doc suggests:

The goal is not to invent a programming language. The goal is to offer just enough programming-esque functionality, such as branching and looping, that is essential for making presentation-related decisions.

于 2013-06-13T06:26:55.213 回答
1

When you have enabled the django.core.context_processors.request it will enable the access to the values of a dictionary-like objects with the . notation. This will convert any Python object into something that the Django template language will understand as it is its own language.

This also applies for the following:

  1. Attribute lookups (eg. myobject.age)
  2. Method calls (eg. myobject.age())
  3. List indices (eg mylist.1)

The thing that is working it behind the scenes is the Context object. You can read more on how it works here and here

And you can compare the Python controlstructure if to Django's template language.

if object:
    myobject.dostuff()

to

{% if object %}
    {{ myobject.dostuff }}
{% endif %}

If you want a closer match to Python you should check out

于 2013-06-13T06:27:26.860 回答