Article written by Abd Allah Diab

A passionate pythonist geek looking for problems, to solve :P

7 responses to “Get Online Users in Django”

  1. Sam

    Thanks for taking out time & putting in the effort to make this available to all as a generic solution.

    This is what makes the Django/Python community so great :)

  2. Abd Allah Diab

    Thanks Sam for coming by, that is my pleasure :)

  3. Rencontre

    Hi,
    I’ve been looking for solutions before to know which users were online.
    At first I looked at your technique but I found that using a new model for the activity and using a middleware to actually hit the database (write operation) costs too much.
    Then I used a technique using an access log. To find the online users, you query the access log and group access entries by user.
    The query in this case is quite slow but you don’t have to add another middleware just to update the last activity.

    I’ve actually found a better technique which is fast and does not hit the database, also you do not need an access log.
    You create memcached entries to know if a user is online.
    Everytime a user logs in, you update another entry in the cache which holds a list of online users (this list can be up to 1MB long, the max size of a memcached entry). Whenever you need the list of online users, you remove offline users from the list and return the resulting list.
    Every page view, you can update the user online status in the cache. If the status goes from offline to online, you add the user to the online list.
    It’s a bit unclear but preserves the app from database hits.

  4. Rencontre

    Hi Abd Allah,
    I forgot to tell that my app actually combines this with a middleware, so you can disable the behaviour just by removing the middleware from the list.
    The only (slight) problem is in the login view : each user login hits the cache, even when the middleware is off. The performance cost is very minimal so it’s just a matter of just enabling or disabling the middleware.
    It would be a perfect solution if the custom login function could tell if the middleware is active.

    1. airtonix

      Any chance you could give us a peek at the source code that demonstrates your approach to this scenario?

  5. Jafte

    made little update, now i can check users status:

    from django.db import models
    from django.contrib.auth.models import User
    from datetime import datetime, timedelta

    class UserActivity(models.Model):
    last_activity_ip = models.IPAddressField()
    last_activity_date = models.DateTimeField(default = datetime(1941, 1, 1))
    user = models.OneToOneField(User, primary_key=True)

    def is_online(self):
    no_active_delta = datetime.now() – self.last_activity_date
    if no_active_delta > timedelta(minutes=21):
    return False
    else:
    return True

Leave a Reply