pythondjangouser-activity

How to filter only one user in online_users


I am Building a BlogApp and I am stuck on a Problem

What i am trying to do

I am trying to access only one user which i have opened the profile online status in template. BUT it is showing all the active users.

What i am doing

I am using online_users_activity to know which user is online.I am using This django_online_users

The Problem

It is showing all the users that are online.

views.py

def online(request,user_id):
    user_status = online_users.models.OnlineUserActivity.get_user_activities(timedelta(hours=87600))
    users = (user for user in user_status)

    context = {'users':users}
    return render(request, 'online.html', context)

I don't know what to do.

Any help would be Appreciated.


Solution

  • You can simply annotate whether the user is online or not yourself by checking if last_activity is greater than some calculated time using Conditional Expressions:

    from django.db.models import BooleanField, Case, Value, When
    from django.shortcuts import get_object_or_404
    from django.utils import timezone
    
    def online(request,user_id):
        min_time = timezone.now() - timedelta(hours=87600)
        queryset = online_users.models.OnlineUserActivity.objects.filter(user_id=user_id).annotate(
            is_online=Case(
                When(last_activity__gte=min_time, then=Value(True)),
                default=Value(False),
                output_field=BooleanField(),
            )
        )
        online_user_activity = get_object_or_404(queryset)
        context = {'online_user_activity': online_user_activity}
        return render(request, 'online.html', context)
    

    Now the user whose profile you are checking would have an annotated field is_online so you can check as:

    {% if online_user_activity.is_online %}
        Online
    {% else %}
        Offline
    {% endif %}