Lesson 46 of 60 – Django Logout System
77%

Django Logout System

A logout system allows an authenticated user to end their current login session and safely leave a protected area of a Django application.

Django provides a built-in logout() function that can be used to log the current user out.

Note: Logout should be handled through Django's authentication system so that the user's authenticated session is properly ended.

1. What is Logout?

Logout means ending the authenticated session of the currently logged-in user.

A simple logout process looks like this:

User is Logged In
        ↓
Clicks Logout
        ↓
logout(request)
        ↓
Session Authentication Removed
        ↓
User is Logged Out

2. Why is Logout Important?

Logout is important when users access private or personal information.

  • Ends the user's authenticated session.
  • Helps prevent unauthorized access on shared devices.
  • Allows users to switch accounts.
  • Completes the login/logout workflow.
  • Provides better session management.

3. Django logout() Function

Django provides the logout() function through django.contrib.auth.

from django.contrib.auth import logout

The function accepts the current request.

logout(request)

4. Creating a Logout View

A simple logout view can call logout() and then redirect the user to another page.

from django.contrib.auth import logout
from django.shortcuts import redirect

def logout_view(request):

    logout(request)

    return redirect("login")

5. Creating a Logout URL

Create a URL pattern that points to the logout view.

from django.urls import path
from . import views

urlpatterns = [

    path(
        "logout/",
        views.logout_view,
        name="logout"
    ),

]

The name logout can be used for URL reversing.

6. Logout Link in Template

A simple logout link can point to the logout URL.

<a href="{% url 'logout' %}">
    Logout
</a>

However, for applications where logout changes authentication state, using a POST request is a common pattern.

7. Logout with POST Form

A logout form can use POST to explicitly submit the logout action.

<form
    method="post"
    action="{% url 'logout' %}"
>

    {% csrf_token %}

    <button type="submit">
        Logout
    </button>

</form>

The CSRF token provides protection for the internal POST request.

8. Checking the Request Method

If you want your custom logout view to accept only POST requests, check the request method.

def logout_view(request):

    if request.method == "POST":

        logout(request)

        return redirect("login")

    return redirect("dashboard")

This makes the intended logout action explicit.

9. Redirecting After Logout

After logout, the user can be redirected to the login page.

logout(request)

return redirect("login")

The destination can also be another public page, such as a home page.

10. Logout and request.user

Before logout, request.user represents the authenticated user.

After logout, the current request is no longer associated with an authenticated user for subsequent authentication checks.

logout(request)

return redirect("login")

11. is_authenticated After Logout

Django provides is_authenticated for checking authentication status.

if request.user.is_authenticated:

    print("User is logged in")

else:

    print("User is logged out")

After logout, later requests from that browser will not be treated as authenticated by Django's authentication system.

12. Protecting Pages After Logout

Private pages should be protected using appropriate authentication checks.

from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):

    return render(
        request,
        "dashboard.html"
    )

If a user is no longer authenticated, they cannot access the protected view as an authenticated user.

13. Login and Logout Together

A complete authentication system normally includes both login and logout.

Login
  ↓
authenticate()
  ↓
login()
  ↓
Protected Page
  ↓
Logout
  ↓
logout()
  ↓
Login Page

14. Complete Logout View

from django.contrib.auth import logout
from django.shortcuts import redirect

def logout_view(request):

    logout(request)

    return redirect("login")

This is a basic custom logout view.

15. Logout View with POST

from django.contrib.auth import logout
from django.shortcuts import redirect

def logout_view(request):

    if request.method == "POST":

        logout(request)

        return redirect("login")

    return redirect("dashboard")

This version performs the logout operation only for a POST request.

16. Logout Button

A button can be placed inside a POST form to create a logout control.

<form
    method="post"
    action="{% url 'logout' %}"
>

    {% csrf_token %}

    <button
        type="submit"
    >
        Logout
    </button>

</form>

17. Showing Logout Only to Logged-in Users

A template can display a logout button only when the current user is authenticated.

{% if user.is_authenticated %}

    <form
        method="post"
        action="{% url 'logout' %}"
    >

        {% csrf_token %}

        <button type="submit">
            Logout
        </button>

    </form>

{% endif %}

18. Login Link for Logged-out Users

The same template can display a login link when the user is not authenticated.

{% if user.is_authenticated %}

    <span>
        Welcome {{ user.username }}
    </span>

{% else %}

    <a href="{% url 'login' %}">
        Login
    </a>

{% endif %}

19. Built-in Logout View

Django also provides authentication views that can be included using django.contrib.auth.urls.

from django.urls import include, path

urlpatterns = [

    path(
        "accounts/",
        include(
            "django.contrib.auth.urls"
        )
    ),

]

This includes Django's standard authentication URL patterns.

20. Built-in Logout URL

When using Django's built-in authentication URLs, the logout route is available under the included authentication URL prefix.

For example, with:

path(
    "accounts/",
    include(
        "django.contrib.auth.urls"
    )
)

the logout URL is conventionally:

/accounts/logout/

21. Logout Template

If you use Django's built-in logout view and configure it to render a logout page, you can provide a template for that purpose.

A simple logout confirmation page might contain:

<h2>
You have been logged out.
</h2>

<a href="{% url 'login' %}">
Login Again
</a>

22. Logout from a Dashboard

A dashboard commonly contains a logout button.

<h1>
Welcome {{ request.user.username }}
</h1>

<form
    method="post"
    action="{% url 'logout' %}"
>

    {% csrf_token %}

    <button type="submit">
        Logout
    </button>

</form>

23. Logout and Session Data

The logout operation removes the authentication information associated with the current session.

This means subsequent requests are not treated as authenticated through that login session.

logout(request)

Always use Django's authentication API instead of trying to manually remove authentication information.

24. Logout and Multiple Accounts

Logout is useful when multiple people use the same computer or browser.

A typical flow is:

User A
  ↓
Login
  ↓
Use Application
  ↓
Logout
  ↓
User B
  ↓
Login

This prevents the next user from simply continuing with the previous authenticated session.

25. Logout Security Practices

  • Use Django's logout() function.
  • Protect logout POST forms with CSRF protection.
  • Use HTTPS in production.
  • Protect private views with authentication checks.
  • Redirect users to an appropriate page after logout.
  • Do not manually manipulate authentication session data.
  • Provide a visible logout option in authenticated areas.

26. Common Logout Mistakes

  • Forgetting to import logout.
  • Calling logout() without passing request.
  • Using an incorrect logout URL.
  • Forgetting the CSRF token in an internal POST logout form.
  • Not protecting dashboard pages.
  • Redirecting to a URL that does not exist.
  • Trying to manually delete authentication session values.

27. Login and Logout URLs Example

from django.urls import path
from . import views

urlpatterns = [

    path(
        "login/",
        views.login_view,
        name="login"
    ),

    path(
        "logout/",
        views.logout_view,
        name="logout"
    ),

    path(
        "dashboard/",
        views.dashboard,
        name="dashboard"
    ),

]

These URLs connect the authentication views with the application.

28. Complete Logout Flow

User Logged In
      ↓
Dashboard
      ↓
Clicks Logout
      ↓
POST Request
      ↓
logout(request)
      ↓
Authentication Session Ends
      ↓
Redirect to Login
      ↓
User Logged Out

29. Complete Logout Example

views.py

from django.contrib.auth import logout
from django.shortcuts import redirect

def logout_view(request):

    if request.method == "POST":

        logout(request)

        return redirect("login")

    return redirect("dashboard")

Template:

<form
    method="post"
    action="{% url 'logout' %}"
>

    {% csrf_token %}

    <button type="submit">
        Logout
    </button>

</form>

30. Django Logout System Summary

Django makes logout simple through its built-in authentication framework.

  • Use logout(request) to log out the current user.
  • Create a logout URL or use Django's built-in authentication URLs.
  • POST forms can be used for logout actions.
  • Use {% csrf_token %} in internal POST forms.
  • Redirect the user after logout.
  • Protect private pages with login_required.
  • Use request.user to access the current user.
  • Use is_authenticated to check authentication status.
  • Always use Django's authentication APIs rather than manually changing authentication state.

📌 Key Points

  • logout() ends the current authenticated session.
  • The logout function receives the current request.
  • Logout can redirect the user to the login page.
  • POST-based logout forms can include CSRF protection.
  • Django provides built-in authentication URL patterns.
  • Private views should be protected with authentication checks.
  • Logout is an important part of a complete authentication system.

🧠 Quick Quiz

Question: Which Django function is used to log out the current user?