I'm working on a project using Python(2.7) and Django(1.11) in which I was needed to implement auto-logout on inactivity for a few minutes or hours.
Note: I have searched a lot and take a look on a various related question but couldn't find any solution for my specific problem, so don't mark it as duplicate, please!
I have achieved this thing by adding some settings in settings.py
as:
SESSION_COOKIE_AGE = 120
SESSION_SAVE_EVERY_REQUEST = True
LOGOUT_REDIRECT_URL = 'mainlogin'
Only for testing purpose, I have set it up for 2 minute.
After 2 minutes then when I refresh the page user get logged out and redirected to the login page but in the backend/database the status of the user is still active
.
I need to use the active users for further processing/execution, so if a user logged out automatically it shouldn't be available is an active user, but it is.
If I manually logged out the user, it's not displaying in the active user anymore, this means the manual logout is working well but the auto log out still shows the user as an active
user.
Here's how I'm getting the active users:
all_active_users = user_table.objects.filter(user_type='a', status=1, approval_status=1, is_active=True)
# further execution
Update: I'm using the custom mode for user which is named as
user_table
and here's what I have tried as suggested by the an answer:
def get_all_logged_in_users():
# Query all non-expired sessions
# use timezone.now() instead of datetime.now() in latest versions of Django
sessions = Session.objects.filter(expire_date__gte=timezone.now())
uid_list = []
# Build a list of user ids from that query
for session in sessions:
data = session.get_decoded()
uid_list.append(data.get('id', None))
# Query all logged in users based on id list
return user_table.objects.filter(id__in=uid_list)
it returns the empty queryset as: active drivers are: <QuerySet []>
even the user of type driver
is logged in.
How can I overcome this issue, so when a user auto logged out, it will not display in active
users.
You're misunderstanding the meaning of is_active
. This field is used by Django to determine whether or not a user is allowed to log in, not whether or not they happen to be logged in at that moment.
Even if you wanted to create your own User
field to store this information it would be difficult to do, since a session expires simply by the passage of time. Nothing actually happens on the server that could trigger a change in a model field.
So, if you need to determine all logged-in users you need to use the session store. Django doesn't offer a straightforward way to do this, but it's certainly possible. This answer shows how to query the Session
table to figure out who is logged in.