How to force a user logout in Django?

Update:

Since Django 1.7, users are automatically logged-out when their password changes. On each request, the current password hash is compared to the value saved in their session and if doesn’t match, the user is logged-out.

So, a simple password update has the effect of logging the user out. You can then disable the account for login, or advise them to use the password reset feature to set a new password and log in again.

Original:

I don’t think there is a sanctioned way to do this in Django yet.

The user id is stored in the session object, but it is encoded. Unfortunately, that means you’ll have to iterate through all sessions, decode and compare…

Two steps:

First delete the session objects for your target user. If they log in from multiple computers they will have multiple session objects.

from django.contrib.sessions.models import Session
from django.contrib.auth.models import User

# grab the user in question 
user = User.objects.get(username="johndoe")

[s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]

Then, if you need to, lock them out….

user.is_active = False
user.save()

Leave a Comment