tags:

views:

169

answers:

3

Hi all

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?

+1  A: 

request.session is a dictionary like any other, so you just use the normal template mechanism for attributes and members:

{{ request.session.name }}

Don't forget to pass the request into the template context, or even better ensure you are using RequestContext and have the request context processor enabled. See the documentation.

Daniel Roseman
A: 

You can pass a request variable to a template and there use:

{{ sequest.session.name }}
Silver Light
+1  A: 

You need to add django.core.context_processors.request to your template context processors. Than 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:

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