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 –
- Create model let say online_user_tracking with the fields ( id, user_id, entry_timestamp )
- When user logs in, add an entry to this model with mentioned fields
- When user log out delete the entry from this model
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…
- [Answered ]-Python.exe crashes when I run manage.py runserver
- [Answered ]-Django: assert 'Many-to-many' relation exists in test
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.
- [Answered ]-How to deal with virtual index in a database table in Django + PostgreSQL
- [Answered ]-Put django file object into tikka server
- [Answered ]-Django – can't run makemigrations: "no such table" even after running reset_db