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?
You need to add
django.template.context_processors.requestto your template context processors. Then you can access them like this:In case you are using custom views make sure you are passing a RequestContext instance. Example taken from documentation:
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 torender_to_response(), but it usesRequestContextautomatically, without a need to pass it explicitly: