djangowebsocketdjango-channels

How to know user is online/offline with django channels?


With Django Channels, can you track which users are online or offline throughout your website? Should every page have a websocket connection? And when a user is online/offline, how can I show the user online/offline in real time.

I have no idea. I only do group chats online users but cant do user online/offline in full website


Solution

  • To show users as online/offline in real-time, you can update their status in the database when they connect/disconnect from the WebSocket. You can periodically check the user's connection status by monitoring their WebSocket connection or using heartbeat signals. Here I will use heart beat version(here i assume that you have an app named chat) : First of all, create a model that store user state which is last_activity like this one : chat/models.py

    class UserActivity(models.Model):
        user          = models.OneToOneField(User, on_delete=models.CASCADE)
        last_activity = models.DateTimeField(default=timezone.now)
    
        def update_activity(self):
            self.last_activity = timezone.now()
            self.save()
    

    If you need more fields, add them and don't forget to add it into your admin panel. Now, you need a middleware to check the user is online or not. chat/middleware.py :

    from django.utils.deprecation import MiddlewareMixin
    from django.utils import timezone
    
    from chat.models import UserActivity
    
    
    class UserActivityMiddleware(MiddlewareMixin):    
    
        def process_request(self, request):
            if request.user.is_authenticated:
                UserActivity.objects.update_or_create(user=request.user, defaults={'last_activity': timezone.now()})
    
    

    Now add this middleware after, Auth middleware like this : core/settings.py :

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',    
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        
        # Here your middleware should go
        'chat.middleware.UserActivityMiddleware',
    ]
    

    Pay attention, Your middleware must be activate after a user logged in. Now you can use this model in which ever way you want, and gets user information in which view that you need.