0
0
Djangoframework~5 mins

Logout view in Django

Choose your learning style9 modes available
Introduction

A logout view lets users safely leave their account on a website. It ends their session so no one else can use their login.

When a user clicks a 'Logout' button to end their session.
To protect user data by clearing login info after use.
When you want to redirect users to a homepage or login page after logout.
To ensure secure access by removing session cookies.
When building any website with user accounts and sessions.
Syntax
Django
from django.contrib.auth import logout
from django.shortcuts import redirect

def logout_view(request):
    logout(request)
    return redirect('home')

The logout(request) function clears the user's session.

After logout, you usually redirect the user to another page like 'home' or 'login'.

Examples
Logs out the user and sends them to the login page.
Django
from django.contrib.auth import logout
from django.shortcuts import redirect

def logout_view(request):
    logout(request)
    return redirect('login')
Logs out the user and shows a simple message instead of redirecting.
Django
from django.contrib.auth import logout
from django.http import HttpResponse

def logout_view(request):
    logout(request)
    return HttpResponse('You have been logged out.')
Using Django's built-in LogoutView class to handle logout and redirect to 'home'.
Django
from django.contrib.auth.views import LogoutView

class CustomLogoutView(LogoutView):
    next_page = 'home'
Sample Program

This example shows a logout view that ends the user session and sends them to a simple homepage. The homepage just shows a welcome message.

Django
from django.contrib.auth import logout
from django.shortcuts import redirect
from django.urls import path
from django.http import HttpResponse

# Logout view function
def logout_view(request):
    logout(request)
    return redirect('home')

# Simple home view to redirect to after logout
def home(request):
    return HttpResponse('Welcome to the homepage!')

# URL patterns
urlpatterns = [
    path('logout/', logout_view, name='logout'),
    path('home/', home, name='home'),
]
OutputSuccess
Important Notes

Always use Django's logout() to clear sessions safely.

Redirecting after logout improves user experience and security.

You can customize logout behavior by subclassing LogoutView.

Summary

Logout view ends user sessions to keep accounts safe.

Use logout(request) and then redirect users.

Django offers both function and class-based logout views.