From what I understood here session_key is the primary key of the session object.
When I inspect request.session, I do find a session object, but it's primary key is not set. It seems to be unsaved. So for now I am fixing this problem by checking in every view whether request.session.session_key exists and if not, calling save().
Does anyone have an explanation to why I only seem to get my hands on unsaved session objects?
If your sessions are set up correctly, there may be two things going on:
Sessions are saved at the end of a request. Even if the session is non-empty, it won't have a primary key until the response middleware has run. The session in the next request will have a primary key.
Empty sessions are always deleted. If your session does not contain any data, the session and cookie are cleared, and the next request will have an empty session with an empty primary key.
These are both valid scenarios when sessions are working correctly. Even with SESSION_SAVE_EVERY_REQUEST
, empty sessions are still cleared.
If for some reason the session cookie isn't set, or it's invalid (because it has been tampered with), the session key will be set to None
as well.