Episode 23 of 32

Logging Users Out

Log users out and destroy their session — call Django logout() and redirect them back to the home page.

Logging Users Out

Logging out means destroying the session so request.user becomes an anonymous user again.

The Logout View

# accounts/views.py
from django.contrib.auth import login, logout

def logout_view(request):
    if request.method == 'POST':
        logout(request)
        return redirect('articles:list')

Use POST for logout — it prevents malicious sites from logging users out via a simple GET link (CSRF protection).

Logout Button in Templates

<!-- Use a form with POST method -->
<form method="POST" action="{% url 'accounts:logout' %}">
    {% csrf_token %}
    <button type="submit">Logout</button>
</form>

What logout() Does

logout(request)

# Internally:
# 1. Flushes the session data from the database
# 2. Clears the session cookie
# 3. request.user becomes AnonymousUser
# 4. User must log in again to access protected pages

Key Takeaways

  • logout(request) destroys the session and clears the cookie
  • Use POST method for logout — not GET — for CSRF security
  • After logout, request.user becomes AnonymousUser
  • Always redirect after logout