using django session inside templates

Abhimanyu picture Abhimanyu · Aug 23, 2012 · Viewed 10.6k times · Source
# views.py
def like(request,option="food",restaurant = 1):
    if request.is_ajax:
        like = '%s_like' % str(option)
        if 'restaurants' in request.session:
            if restaurant not in request.session['restaurants']:
                request.session['restaurants'][restaurant] = {}
            x = request.session['restaurants'][restaurant].get(str(like),False)
            if x:
                return HttpResponse(False)
            else:
                request.session['restaurants'][restaurant][str(like)] = True
                request.session.modified = True

        else:
            request.session['restaurants'] = {}
        request.session.modified = True

I am using context_instance = RequestContext(request) so that session variable is available, while rendering response. My template:

{% if request.session.restaurants.rest.id.food_like %}
working
{% else %}
    failed
{% endif %}

My view session key looks like this :

request.session["restaurants"][restaurant][like] = True

where restaurant is the restaurant id, and like could be one of " "food_like", "service_like", "special_like".

So how am i supposed to access it in my templates? For example if i use

request.session.restaurants.rest.id.food_like 

it won't work for sure.

Answer

jpic picture jpic · Aug 23, 2012

You might not have django.core.context_processors.request in your settings.TEMPLATE_CONTEXT_PROCESSORS.

You can try to print {{ request }} in the template, if it shows nothing then you don't have it.

You can also check it with ./manage.py shell:

from django.conf import settings
print settings.TEMPLATE_CONTEXT_PROCESSORS

If django.core.context_processors.request is not there, then copy TEMPLATE_CONTEXT_PROCESSORSfrom the shell output into your settings.py, and add django.core.context_processors.request to this list.