Set Django Logout Redirect URL
Here's how to set up a URL to redirect to after logout in Django.
Make a URL Path
In one of your app's urls.py
files, create the urlpattern:
from django.contrib.auth import views as auth_views
from django.urls import path
from myproj import settings
urlpatterns = [
path('logout/', auth_views.LogoutView.as_view(next_page=settings.LOGOUT_REDIRECT_URL), name='myapp_logout'),
]
Optionally create a setting
The above code uses a setting of LOGOUT_REDIRECT_URL
to store the location of the redirect. I got this pattern from looking at other docs and qna. But I don't think it's required. If you learn otherwise, please let me know.
Anyway, set it up in settings.py
:
LOGOUT_REDIRECT_URL = '/'
Take Notice
logout/
url path is requireddjango.contrib.auth.LogoutView.as_view
is what you redirect to.- You do not need to pass a
template
kwarg required - Thus, no
myapp/logout.html
template is required either - The
next_page
kwarg is required LOGOUT_REDIRECT_URL
by itself is insufficient
Try it out
python manage.py runserver
xdg-open localhost:8000/logout
See that you are now redirected to /
.