Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

Django: accessing session variables from within a template?

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?

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.

(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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

{{ request.session.name }}

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))

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...