Search code examples
djangodjango-sessions

Django, track session even as user logs in and out


How do I track sessions in Django even after a user has logged in or out? I am using Django authentication.

For example, a user lands on the main page, and maybe follows a few links on my site. Then he logs in. Logs out. Follows some links. I want to track that this is the same user, or at least someone using the same browser session.

I am currently tracking

request.user.id

which is, of course, specific for a logged in user.

I thought I could use

request.session.session_key

to track the session, but the session_key changes when the user logs in and again when he logs out.

(What I really want to know is whether the person who lands on my page also logs in / signs up.)


Solution

  • Don't rely on the session cookie for this (because indeed, Django automatically rotates it across login / logouts — mainly to prevent session fixation attacks).

    Instead, just create your own cookie, and track users that way.