3

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.

Jeremy
  • 22,188
  • 4
  • 68
  • 81
Snels Nick
  • 925
  • 3
  • 13
  • 25
  • 2
    Why would you do that query? Why not just access `request.session` directly? – Daniel Roseman May 17 '12 at 18:27
  • I have a table that references the django_session table like: session = models.ForeignKey(Session) When I create an instance of it, using request.session for example it gives me the following error: Cannot assign "": "Visitor.session" must be a "Session" instance. That is why I am trying to query the session table in order to get a "Session" instance. – Snels Nick May 17 '12 at 19:58
  • 1
    Do you actually have a session key when you are hitting the db? New sessions are being created only in `process_response` on the session middleware - because they need to store anything from the view, and can't do that before the view is fully processed. – ilvar May 18 '12 at 05:12

2 Answers2

5

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()
Community
  • 1
  • 1
Snels Nick
  • 925
  • 3
  • 13
  • 25
1

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.

Furbeenator
  • 8,106
  • 4
  • 46
  • 54