[Django]-How can I logout a user in Django?

32👍

You can log them out using

from django.contrib.auth import logout

if <your authentication validation logic>:
    logout(request) 

… from within any view.

logout() Django docs here.

1👍

In addition to the login_required decorator, you could use the user_passes_test decorator to test if the user is still active.

from django.contrib.auth import user_passes_test

def is_user_active(user):
    return user.is_active

@user_passes_test(is_user_active, login_url='/your_login')
def your_function(request):
    ....

1👍

You can use a session backend that lets you query and get the sessions of a specific user. In these session backends, Session has a foreign key to User, so you can query sessions easily:

Using these backends, deleting all sessions of a user can be done in a single line of code:

# log-out a user
user.session_set.all().delete()

Disclaimer: I am the author of django-qsessions.

Leave a comment