[Answered ]-Check for online users in django(django 1.10 python 3.5)

2đź‘Ť

âś…

After a lot of searching and re-searching i finally got the answer!

In views.py

def get_current_users(request):
    active_sessions = Session.objects.filter(expire_date__gte=timezone.now())
    user_id_list = []
    for session in active_sessions:
        data = session.get_decoded()
        user_id_list.append(data.get('_auth_user_id', None))
    return User.objects.filter(id__in=user_id_list)


def userList(request):
    users = User.objects.all()
    online = get_current_users([])
    context = {
        "users_list": users,
        "online_list": online,
    }
    return render(request, 'Index/users.html',context)

Create this two views.(as a beginner that the best i could do feel free to manipulate the code)

in urls.py

url(r'^users/$', views.userList, name="user"),

then in users.html

{% extends "Index/header.html" %} {% block content %}
{% for user in users_list %}
{{ user }}
{% if user in online_list %}
online
{%else%}
offline
{% endif %}
{% endfor%}

{% endblock %}

What its basically doing is :

First its collecting all the logged in users
then gathering all listed users the cross checking weather users in the user list with logged in user list. If true its printing online if not its printing offline beside the user name.

0đź‘Ť

To detect whether a user is online or offline you can follow the below
strategy.

Create new DB table which will track the records of all the online
users.

Steps –

  1. Create model let say online_user_tracking with the fields ( id, user_id, entry_timestamp )
  2. When user logs in, add an entry to this model with mentioned fields
  3. When user log out delete the entry from this model
  4. Now it could be possible that user may not log out properly and go away, in that case, you have to use keep alive (Polling) mechanism as
    mentioned below –

    Polling ( Keep alive ) –

    When user login to your site the entry will be created to the model “online_user_tracking”. Then on every 5 second’s you have to
    update its timestamp field for the current logged in user_id. Now on
    the backend we have to write a script wich will be executed in every 5
    seconds ( May have to schedule a CRON job on the server ) and check if
    any records have not updated it’s timestamp in last 3 minutes those
    entries should be deleted.
    That’s how we can keep the records of online and offline users of the site.

Hope this explanation will help…

👤Vee Mandke

0đź‘Ť

You can use django-socketio and define it to give the user status to the server from the client HTML. This will keep polling to the server about the status change.

Leave a comment