Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to access session_key in middleware

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.

like image 934
Snels Nick Avatar asked Dec 31 '25 23:12

Snels Nick


1 Answers

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()
like image 171
Snels Nick Avatar answered Jan 04 '26 00:01

Snels Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!