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.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.