Django:从模板中访问会话变量? [英] Django: accessing session variables from within a template?

查看:118
本文介绍了Django:从模板中访问会话变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Django中设置一个会话变量,例如:

If I set a session variable in Django, like:

request.session["name"] = "name"

有没有办法可以从模板中访问它,或者我必须从在一个视图中,然后将其传递给模板?

Is there a way I can access it from within a template, or do I have to retrieve it from within a view, and then pass it to a template?

请求,因为我有大约10个小会话变量,我想在模板中访问,并传递所有10从视图到模板可能会有点凌乱。

Asking because I have around 10 little session variables that I'd like to access within a template, and passing all 10 from the view to the template could get a bit messy.

(我必须使用会话变量,因为它是一个HttpResponseRedirect,但将变量存储在数据库中是为我的目的而过度使用。)

(I have to use session variables because it's a HttpResponseRedirect, but storing the variables in a database is overkill for my purposes.)

所以 - 直接在模板中抓取会话变量的任何方法?

So - any way to grab session variables directly within a template?

推荐答案

您需要添加 django.core。 context_processors.request 到您的模板上下文处理器。那么你可以这样访问它们:

You need to add django.core.context_processors.request to your template context processors. Then you can access them like this:

{{ request.session.name }}

如果您使用自定义视图,请确保传递了RequestContext实例。 文档采用的示例:

In case you are using custom views make sure you are passing a RequestContext instance. Example taken from documentation:

from django.shortcuts import render_to_response
from django.template import RequestContext

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))

更新2013:根据我仍然收到的这个答案,人们仍然觉得有用,超过三年原来是写的但请注意,尽管上述视图代码仍然有效,但是现在有一种简单的方式可以做到这一点。 render() 是一个与 render_to_response()非常相似的函数,但它自动使用 RequestContext ,而不需要传递显式地:

Update 2013: Judging by the upvotes I'm still receiving for this answer, people are still finding it helpful, more than three years after it was originally written. Please note however, that although the view code above is still valid, nowadays there is a much simpler way of doing this. render() is a function very similar to render_to_response(), but it uses RequestContext automatically, without a need to pass it explicitly:

from django.shortcuts import render

def some_view(request):
    # ...
    return render(request, 'my_template.html', my_data_dictionary)

这篇关于Django:从模板中访问会话变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆