[Django]-Django: How to access session_key in middleware

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()
๐Ÿ‘คSnels Nick

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

Leave a comment