How to Configure Where to Redirect After a Log Out in Django?
Last Updated :
04 Nov, 2024
One common requirement in many Django applications is redirecting users to a specific page after they log out. By default, Django redirects users to the login page, but this can be customized to suit our needs.
There are two general methods to redirect users to the specific URL after they log out.
- Create a custom logout view and add the redirection logic.
- Customize the LogoutView and add success_url
- Modify the LOGOUT_REDIRECT_URL in the settings.py file.
In this article, we will be discussing how to redirect to a specific URL after logging out of our Django web application.
Let's first quickly set up a Django project for the demonstration purpose.
python -m venv environment
environment\Script\activate
pip install django
django-admin startproject test_project
python manage.py startapp authentication
# Run initial migrate command
python manage.py migrate
Create the following templates for each endpoints in the templates directory in the root folder: login, register, and home.
test_project\
templates\
index.html
login.html
register.html
home.html
When the user visits the root URL, they will see the index templates containing three buttons pointing to login, register, index and home pages.
The home page is restricted and only visible to logged in user. Also, the home page will slightly change according to our redirection technique, so refer individually to see its HTML code.
HTML
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Index Page</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
height: 100vh;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
}
.content-container {
text-align: center;
}
h1 {
font-size: 2.5em;
color: #333;
margin-bottom: 20px;
}
.button-container button {
background-color: #007bff;
color: white;
padding: 15px 30px;
margin: 10px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease;
}
.button-container button:hover {
background-color: #0056b3;
}
@media (max-width: 600px) {
.button-container button {
width: 100%;
margin: 5px 0;
}
}
</style>
</head>
<body>
<div class="content-container">
<h1>Index Page</h1>
<div class="button-container">
<button onclick="window.location.href='/login';">Login</button>
<button onclick="window.location.href='/register';">Register</button>
<button onclick="window.location.href='/home';">Home</button>
</div>
</div>
</body>
</html>
HTML
<!-- register.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<title>Registration Form</title>
</head>
<body>
<div class="container mt-5">
<form class="col-6 mx-auto card p-3 shadow-lg" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h1 style="text-align: center;"><span style="color: green;">GeeksforGeeks</span></h1>
<h3>Register</h3>
<hr>
{% if messages %}
<div class="alert alert-primary" role="alert">
{% for message in messages %}
{{ message }}
{% endfor %}
</div>
{% endif %}
<div class="form-group">
<label for="exampleInputEmail1">First name</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
placeholder="Enter First name" name="first_name" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Last name</label>
<input type="text" name="last_name" class="form-control" id="exampleInputEmail1"
aria-describedby="emailHelp" placeholder="Enter Last name" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Username</label>
<input type="text" class="form-control" name="username" id="exampleInputEmail1"
aria-describedby="emailHelp" placeholder="Enter email" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" name="password" id="exampleInputPassword1"
placeholder="Password" required>
</div>
<p>Already have an account <a href="/login/">Login</a> </p>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
HTML
<!-- login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<form class="col-6 mx-auto card p-3 shadow-lg" method="post" enctype="multipart/form-data">
<h1 style="text-align: center;"><span style="color: green;">GeeksforGeeks</span></h1>
{% csrf_token %}
<h3>Login</h3>
<hr>
{% if messages %}
<div class="alert alert-primary" role="alert">
{% for message in messages %}
{{ message }}
{% endfor %}
</div>
{% endif %}
<div class="form-group">
<label for="exampleInputEmail1">Username</label>
<input type="text" class="form-control" name="username" id="exampleInputEmail1" aria-describedby="emailHelp"
placeholder="Enter username" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password" required>
</div>
<p>Don't have an account <a href="/register/">Register</a> </p>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
HTML
<!-- home.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
height: 100vh;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
}
.container {
text-align: center;
padding: 40px;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
max-width: 500px;
}
h1 {
color: green;
font-weight: bold;
font-size: 2em;
margin-bottom: 20px;
}
img {
width: 60%;
margin-bottom: 20px;
}
button {
background-color: #007bff;
color: white;
padding: 15px 30px;
margin: 10px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #0056b3;
}
@media (max-width: 600px) {
.container {
padding: 20px;
width: 90%;
}
button {
width: 100%;
margin: 5px 0;
}
}
</style>
</head>
<body>
<div class="container">
<h1>Welcome to Geeksforgeeks. This page is only visible to users which are logged in.</h1>
<form method="POST" action="{% url 'logout' %}">
{% csrf_token %}
<button class="btn btn-primary">Logout</button>
</form>
</div>
</body>
</html>
Let's add logic to the home, login, index and register endpoints. We will later add logic to redirect user once they logout.
authentication/views.py
Python
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth import logout
@login_required(login_url="/login/")
def home_page(request):
return render(request, 'home.html')
def index_page(request):
return render(request, 'index.html')
def login_page(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
if not User.objects.filter(username=username).exists():
messages.error(request, 'Invalid Username')
return redirect('/login/')
user = authenticate(username=username, password=password)
if user is None:
messages.error(request, "Invalid Password")
return redirect('/login/')
else:
login(request, user)
return redirect('/home/')
return render(request, 'login.html')
def register_page(request):
if request.method == 'POST':
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
username = request.POST.get('username')
password = request.POST.get('password')
user = User.objects.filter(username=username)
if user.exists():
messages.info(request, "Username already taken!")
return redirect('/register/')
user = User.objects.create_user(
first_name=first_name,
last_name=last_name,
username=username
)
user.set_password(password)
user.save()
messages.info(request, "Account created Successfully!")
return redirect('/register/')
return render(request, 'register.html')
Redirect User After logout
We can follow any one of the techniques mentioned below to implement the redirection process after the user has logged out.
1. Creating Logout Method Inside Views.py
Here, we are creating the logout_view to redirect user to the root url.
authentication/views.py
Python
# ...
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
# ...
@login_required
def logout_handler(request):
logout(request)
return redirect('/')
Now, let's connect all the views to the specific URL.
test_project/urls.py
Python
from django.contrib import admin
from django.urls import path
from authentication.views import *
urlpatterns = [
path('', index_page, name='index_page'),
path('home/', home_page, name="home_page"),
path("admin/", admin.site.urls),
path('login/', login_page, name='login_page'),
path('register/', register_page, name='register'),
path("logout/", logout_handler, name="logout"),
]
2. Override LogoutView
Another technique is to use override LogoutView method and set the success_url. Once, a user logs out, he will be redirected to the success_url.
authentication/views.py
Python
from django.contrib.auth.views import LogoutView
# ...
class CustomLogoutView(LogoutView):
# Must be a valid url name
success_url = 'index_page'
Now, let's modify the URLs for this view.
test_project/urls.py
Python
# ...
urlpatterns = [
# ...
path("logout/", CustomLogoutView.as_view(), name="logout"),
]
3. Using LOGOUT_REDIRECT_URL
The third and the simplest approach to redirect a user to a specific URL is by defining LOGOUT_REDIRECT_URL in the settings.py file.
settings.py
Python
# ...
LOGOUT_REDIRECT_URL = 'home_page'
In this case, the user will always be redirected to the 'home_page'.
Output:
We can choose any of the above method to set the redirection of user once they logout. The optimal way would be use third third method in any of the project.