在模板中使用django会话

Abh*_*nyu 4 python django django-templates django-sessions

# views.py
def like(request,option="food",restaurant = 1):
    if request.is_ajax:
        like = '%s_like' % str(option)
        if 'restaurants' in request.session:
            if restaurant not in request.session['restaurants']:
                request.session['restaurants'][restaurant] = {}
            x = request.session['restaurants'][restaurant].get(str(like),False)
            if x:
                return HttpResponse(False)
            else:
                request.session['restaurants'][restaurant][str(like)] = True
                request.session.modified = True

        else:
            request.session['restaurants'] = {}
        request.session.modified = True
Run Code Online (Sandbox Code Playgroud)

我正在使用,context_instance = RequestContext(request)以便会话变量可用,同时渲染响应.我的模板:

{% if request.session.restaurants.rest.id.food_like %}
working
{% else %}
    failed
{% endif %}
Run Code Online (Sandbox Code Playgroud)

我的视图会话密钥如下所示:

request.session["restaurants"][restaurant][like] = True
Run Code Online (Sandbox Code Playgroud)

restaurant餐馆ID 在哪里,可能是"food_like","service_like","special_like"之一.

那么我应该如何在我的模板中访问它?例如,如果我使用

request.session.restaurants.rest.id.food_like 
Run Code Online (Sandbox Code Playgroud)

它肯定不会起作用.

jpi*_*pic 9

您可能没有django.core.context_processors.request在你的settings.TEMPLATE_CONTEXT_PROCESSORS.

您可以尝试{{ request }}在模板中打印,如果它没有显示任何内容,那么您没有.

您也可以使用./manage.py shell进行检查:

from django.conf import settings
print settings.TEMPLATE_CONTEXT_PROCESSORS
Run Code Online (Sandbox Code Playgroud)

如果django.core.context_processors.request不存在,TEMPLATE_CONTEXT_PROCESSORS则从shell输出复制到settings.py,然后添加django.core.context_processors.request到此列表中.