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


You can log them out using

from django.contrib.auth import logout

if <your authentication validation logic>:

… from within any view.

logout() Django docs here.


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):


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

Disclaimer: I am the author of django-qsessions.

Leave a comment