John Gordon
John Gordon

Reputation: 33335

How can I tell if a Django session is new?

Within a view, is there an easy way to tell if this is the very first hit in a session?

I looked for something obvious like comparing session-create-date to session-last-accessed-date, but those fields don't seem to exist.

I could set a custom key in the session data, and then if the key is missing assume it's a new session, but I wondered if there were some cleaner way.

Thanks!

Upvotes: 7

Views: 878

Answers (2)

Judy T Raj
Judy T Raj

Reputation: 1844

You could use the session_key. If request.session.session_key is None, that means the session object is new and hasn't been saved to the db yet.

Upvotes: 0

Torsten Engelbrecht
Torsten Engelbrecht

Reputation: 13486

How about you calculate it via settings.SESSION_COOKIE_AGE minus my_session.get_expiry_age(). The closer to 0, the newer the session. Not sure though this is always zero for a first-hit session.

Upvotes: 1

Related Questions