LOGOUT_REDIRECT_URL doesn't redirect to the desired page

107 Views Asked by At

I'm new to Django and run to the problem that I want to logout from an account by one click using 'django.contrib.auth.urls'. Here is my 'urls.py'

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

home.html

{%  if user.is_authenticated %}
     <p>Hi, {{ user.username }}</p>
     <p><a href="{% url 'logout' %}">Log out</a></p>          
{% else %}
     <p>You are not logged in</p>
     <p><a href="{% url 'login'  %}">Log In</a></p>
{% endif %}       

settings.py

LOGOUT_REDIRECT_URL = "home"
LOGIN_REDIRECT_URL = "home"

I know that by default I should be redirected to /accounts/logout, when I click on href link, but I set LOGOUT_REDIRECT_URL to home. LOGIN_REDIRECT_URL = "home" on the other hand works perfectly I read a lot of topics on this problem but none of the solutions helped me

I tried setting path manually. It worked in a sense that it I stayed at the same page, but I didn't log out from my account

path('', auth_views.LogoutView.as_view(next_page=settings.LOGOUT_REDIRECT_URL), name='logout'),

1

There are 1 best solutions below

0
JEndahl53 On

We must be using the same book, @user23355404.

There was a change with Django 5, and that technique of logging out no longer works. You need need to use a form and do a "post". The change was identified in this bug report

Will Vincent (book author) also explains the change and how to fix it at this site.

You need to change your logout process to:

<form action="{% url 'logout' %}" method="post>
    {% csrf_token %}
    <button type="submit">Log Out</button
</form>

You will now see a Log Out button rather than a link. I've tested this and it works for me. I hope that helps.