Logout with logout()
A snippet showing how to log out users and clear their sessions in Django.
# views.py
from django.contrib.auth import logout
from django.shortcuts import redirect
def logout_view(request):
logout(request)
return redirect('login') # Redirect to login page after logout
<!-- logout is usually triggered via a link or button -->
<a href="{% url 'logout' %}">Logout</a>
Explanation:
-
We use
logout()to end the current user session cleanly. - This function removes all session data, making the user anonymous instantly.
- After logout, we redirect users to the login page - this improves UX and avoids confusion.
- You can place a logout link in your navbar or dropdown menu for easy access.
- Category Authentication & Authorization
- Total Views 1614
- Last Modified 10 September, 2025
- Tags #logout #authentication #fbv #session
Previous snippet
Login with authenticate and login (FBV)
Next snippet