@jose_gulgowski
There are different approaches to getting the number of active users on your Django website, depending on how you define "active". Here are some suggestions:
1 2 3 4 5 |
from django.contrib.sessions.models import Session from django.utils import timezone active_sessions = Session.objects.filter(expire_date__gte=timezone.now()) active_users_count = active_sessions.count() |
This will give you the number of currently active sessions, which you can assume to be the number of active users.
1 2 3 4 5 6 7 8 9 10 |
class ActiveUsersMiddleware: def __init__(self, get_response): self.get_response = get_response self.active_users_count = 0 def __call__(self, request): response = self.get_response(request) if request.user.is_authenticated: self.active_users_count += 1 return response |
This middleware counts the number of authenticated users who make requests to your website. To use it, add it to your MIDDLEWARE
setting in settings.py
and then access the active_users_count
attribute from your views or templates.
1 2 3 4 5 |
MIDDLEWARE = [ # ... 'path.to.ActiveUsersMiddleware', # ... ] |
Note that these approaches may not be completely accurate or may have some performance impact on your website, so use them judiciously.