Django: accessing session variables from within a template?

前端 未结 9 1532
陌清茗
陌清茗 2020-11-28 20:23

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, o

9条回答
  •  萌比男神i
    2020-11-28 21:05

    You need to add django.core.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)
    

提交回复
热议问题