python - 在模板中使用 django session

标签 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

我正在使用 context_instance = RequestContext(request) 以便 session 变量可用,同时呈现响应。我的模板:

{% if request.session.restaurants.rest.id.food_like %}
working
{% else %}
    failed
{% endif %}

我的 View session key 如下所示:

request.session["restaurants"][restaurant][like] = True

其中 restaurant 是餐厅 ID,like 可以是“food_like”、“service_like”、“special_like”之一。

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

request.session.restaurants.rest.id.food_like 

肯定行不通。

最佳答案

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

您可以尝试在模板中打印{{ request }},如果没有显示则说明您没有。

你也可以用 ./manage.py shell 来查看:

from django.conf import settings
print settings.TEMPLATE_CONTEXT_PROCESSORS

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

关于python - 在模板中使用 django session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12096440/

相关文章:

django - 为什么我的 Django 网站出现网络错误?

django - 将什么传递给模板、对象或字段?

javascript - Django 模板中的 List.pop() 没有 for 循环

python - django 模板 - 循环遍历 2 个查询集

递归后返回 None 的 Python 函数

python - 从索引开始遍历 python 字符串

python - 将 HTTP 服务器绑定(bind)到本地 ip :port so that others in LAN can see it?

mysql - 如何配置 Django 以使用 mysql

python - 有效地将元组列表转换为具有相应总和的集合

python - Django 没有正确创建测试数据库