I'm unable to access the session_key
in my custom Django middleware. I try to access it using:
session = Session.objects.get(pk=request.session._session_key)
or
session_key = request.COOKIES[settings.SESSION_COOKIE_NAME]
session = Session.objects.get(pk=session_key)
I get the error:
Session matching query does not exist.
I have put my middleware at the end of MIDDLEWARE_CLASSES
and after django.contrib.sessions.middleware.SessionMiddleware
in my settings.py
file.
I can set session keys in the middleware, but it appears as if the session_key is only generated/accessible after the full page is displayed. Because when the page is displayed for the first time {{ request.session.session_key }}
returns None
in my template. When I refresh the page I get to see the session_key
. Any tips on how I can access the session_key
are very welcome.