Using django session inside templates

# 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 use context_instance = RequestContext(request) so that the session variable is available instead of rendering. My template:

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

My browsing session is as follows:

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

where restaurant is the identifier of the restaurant, and, as it may be, one of "food_like", "service_like", "special_like".

So, how should I access it in my templates? For example, if I use

 request.session.restaurants.rest.id.food_like 

it will not work for sure.

+4
source share
2 answers

You may not have django.core.context_processors.request in settings.TEMPLATE_CONTEXT_PROCESSORS .

You can try typing {{ request }} in the template, if it doesnโ€™t show anything, then you donโ€™t have it.

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

 from django.conf import settings print settings.TEMPLATE_CONTEXT_PROCESSORS 

If django.core.context_processors.request does not exist, copy TEMPLATE_CONTEXT_PROCESSORS from the shell output to your settings.py and add django.core.context_processors.request to this list.

+9
source

In addition to @ jpic's answer.
Instead of copying the contents of TEMPLATE_CONTEXT_PROCESSORS from the shell, you can do the following:

 from django.conf import global_settings TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + ( "django.core.context_processors.request", ) 

Thus, your global settings will be saved.
Be sure to keep the trailing comma so python can treat this as a tuple

+4
source

All Articles