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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With