Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 1.5 Session Key is None

Tags:

django

For some reason, doing {{ request.session.session_key }} in the template gives me a None value. After some searching, came across this post that mentioned using request.session._session_id but using that in the template gives me an error:

Variables and attributes may not begin with underscores: 'request.session._session_key'

My understanding of sessions in Django is that the moment a user loads a page (any page), even if he is anonymous, a session_id is assigned to that particular session. Is my understanding wrong and also, is this where using [SESSION_SAVE_EVERY_REQUEST] is supposed to come in?

I'm using database backend as my session store.

like image 635
super9 Avatar asked May 04 '13 03:05

super9


1 Answers

To answer my own question:

It is still possible to access the session key using {{ request.session.session_key }}. However, the docs mention that a session will only be created if you've saved/modified the session.

By default, Django only saves to the session database when the session has been modified – that is if any of its dictionary values have been assigned or deleted:

So in my case, the session wasn't being set because I wasn't manipulating it. Using SESSION_SAVE_EVERY_REQUEST will indeed solve the problem globally. In my use case, I only needed it on a particular view function so it was a simple matter of doing this:

if not request.session.get('has_session'):
    request.session['has_session'] = True
like image 79
super9 Avatar answered Nov 03 '22 00:11

super9