Reputation: 955
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.
Upvotes: 3
Views: 7809
Reputation: 955
I managed to get it to work. It turns out that normally the session is only saved after the complete page is rendered.
I managed to save the session prematurely in my middleware using:
request.session.save()
I could then save my model like (note the _id after session, which allows you to set the foreign key using only an integer or varchar in my case):
visitor = Visitor()
visitor.session_id = request.session.session_key
visitor.save()
Upvotes: 5
Reputation: 8285
I was able to do this with the following, does it work for you?
Session.objects.get(session_key=request.session.session_key)
If not, perhaps @ilvar is correct that you attempting to access the session before it is active.
Upvotes: 1