7

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!

John Gordon
  • 29,573
  • 7
  • 33
  • 58

2 Answers2

1

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.

Torsten Engelbrecht
  • 13,318
  • 4
  • 46
  • 48
  • Yeah, I thought about that too. But like you say, the difference isn't guaranteed to be zero for a new session. – John Gordon Aug 29 '12 at 16:01
  • Except this I don't see a built-in way to do it. You might be able to find a workaround, extending session model (db sessions) or saving session creation somewhere else. Another idea is to save a flag in the session (on creation), a boolean or something which you toggle first time the session is used. – Torsten Engelbrecht Aug 30 '12 at 01:46
0

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.

Judy T Raj
  • 1,755
  • 3
  • 27
  • 41