[Django]-How can I know if a specific user, not the current requesting user, is logged in Django?


No in-built method exists to do what you’re looking for, however there is an app that you can plugin to your project that lets you do what you want. It’s called django-tracking and you can find it here: https://github.com/codekoala/django-tracking

EDIT Whoops! I got beat to it, but basically what Mark Lavin said.


The short answer is you can’t; at least not with anything built-in to Django. To know if any user in the database is logged in you essentially are asking if the user is tied to an active session. But you cannot query the session table (short of querying all active sessions) for the user id since this information is stored as pickled data. And even if you did this is not entirely meaningful depending on how long the session cookie lasts (default 2 weeks).

So what can you do? One thing you can query about the user is the last time they logged in. For instance you could get user which last logged in less than 10 minutes ago:

from datetime import datetime, timedelta
from django.contrib.auth.models import User

cutoff = datetime.now() - timedelta(minutes=10)
active = User.objects.filter(last_login__gt=cutoff)

Another thing you can do is track this on your own. In fact there is an app which does just that called django-tracking.

Leave a comment