Django - How to track if a user is online/offline in realtime? Django - How to track if a user is online/offline in realtime? django django

Django - How to track if a user is online/offline in realtime?


Using WebSockets is definitely the better approach.

Instead of having a binary "online"/"offline" status, you could count connections: When a new WebSocket connects, increase the "online" counter by one, when a WebSocket disconnects, decrease it. So that, when it is 0, then the user is offline on all devices.

Something like this

@database_sync_to_asyncdef update_user_incr(self, user):    UserProfile.objects.filter(pk=user.pk).update(online=F('online') + 1)@database_sync_to_asyncdef update_user_decr(self, user):    UserProfile.objects.filter(pk=user.pk).update(online=F('online') - 1)


The best approach is using Websockets.

But I think you should store not just the status, but also a session key or a device identification. If you use just a counter, you are losing valuable information, for example, from what device is the user connected at a specific moment. That is key in some projects. Besides, if something wrong happens (disconnection, server crashes, etc), you are not going to be able to track what counter is related with each device and probably you'll need to reset the counter at the end.

I recommend you to store this information in another related table:

from django.db import modelsfrom django.conf import settingsclass ConnectionHistory(models.Model):    ONLINE = 'online'    OFFLINE = 'offline'    STATUS = (        (ONLINE, 'On-line'),        (OFFLINE, 'Off-line'),    )    user = models.ForeignKey(        settings.AUTH_USER_MODEL,        on_delete=models.CASCADE    )    device_id = models.CharField(max_lenght=100)    status = models.CharField(        max_lenght=10, choices=STATUS,        default=ONLINE    )    first_login = models.DatetimeField(auto_now_add=True)    last_echo = models.DatetimeField(auto_now=True)    class Meta:        unique_together = (("user", "device_id"),)

This way you have a record per device to track their status and maybe some other information like ip address, geoposition, etc. Then you can do something like (based on your code):

@database_sync_to_asyncdef update_user_status(self, user, device_id, status):    return ConnectionHistory.objects.get_or_create(        user=user, device_id=device_id,    ).update(status=status)

How to get a device identification

There are plenty of libraries do it like https://www.npmjs.com/package/device-uuid. They simply use a bundle of browser parameters to generate a hash key. It is better than use session id alone, because it changes less frencuently.

Tracking away status

After each action, you can simply update last_echo. This way you can figured out who is connected or away and from what device.


Advantage: In case of crash, restart, etc, the status of the tracking could be re-establish at any time.