How can I logout a user in Django? How can I logout a user in Django? python python

How can I logout a user in Django?


You can log them out using

from django.contrib.auth import logoutif <your authentication validation logic>:    logout(request) 

... 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_testdef 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 useruser.session_set.all().delete()

Disclaimer: I am the author of django-qsessions.