0

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.

  • The **`request.user`** is the user who has an **active login session***, which means, `request.user` will be ***always*** active. – JPG Mar 14 '21 at 16:45
  • Right but when i open others profile then i want to show there. Can i filter `user_id` in this ? –  Mar 14 '21 at 16:46
  • maybe. It depends on the behavior of **`get_user_activities(...)`** function. – JPG Mar 14 '21 at 17:03

1 Answers1

-1

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 %}
Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
  • It is saying `name 'OnlineUserActivity' is not defined` . –  Mar 14 '21 at 17:14
  • @Space you should write `online_users.models.OnlineUserActivity` instead since you haven't directly imported the model. I assume in the answer that the model is imported. – Abdul Aziz Barkat Mar 14 '21 at 17:15
  • When i use `online_users.models.OnlineUserActivity.filter` instead of `OnlineUserActivity.objects.filter` then it is showing **type object 'OnlineUserActivity' has no attribute 'filter'**. –  Mar 14 '21 at 17:25
  • @Space Don't replace the `objects` it is the model manager. I have edited the answer you can refer from it. – Abdul Aziz Barkat Mar 14 '21 at 17:26