Get Online Users in Django

I was upgrading my Django Bookmarks site, and I wanted to list the online users. I searched the internet and I found a simple method, but it doesn’t work properly. So I developed my own method.

Why the simple method didn’t work?

The problem with it is that it depends on the last login date in the user model. This field is updated on every login for the user.

Imagine the following scenario:
* The user X logs in @ 1:00 pm.
* The user X posts a new post @ 1:30 pm.
* The user X comments on a previous post @ 1:35 pm.
* The user X leaves the website @ 1:40 pm.
* The user X comes back to the website @ 3:00 pm.
* The user X is logged in since the session cookie has not expired yet.
* The user X posts a new post @ 3:15 pm.
* A guest enters the website, and looks at the online users corner.

The guest won’t see X’s name in the list of online users, simply because X’s last login date is @ 1 pm, even though user X is now online and he has just posted a new post.

Continue reading “Get Online Users in Django”