VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-configure-where-to-redirect-after-a-log-out-in-django/

⇱ How to Configure Where to Redirect After a Log Out in Django? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Configure Where to Redirect After a Log Out in Django?

Last Updated : 4 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.

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

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

Now, let's connect all the views to the specific URL.

test_project/urls.py

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

Now, let's modify the URLs for this view.

test_project/urls.py

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

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.

Comment
Article Tags: