How do I log out of django?
Html code
{% if request.user %}
<a href="{% url 'main:logout' %}">
</a>
{% else %}
<a href="{% url 'main:registration' %}">
</a>
{% endif%}
settings.py
LOGIN_REDIRECT_URL = 'main/index'
views.py
def logout(request):
logout(request)
urls.py
from django.conf.urls import url
from . import views
from django.conf import settings
urlpatterns = [
url(r'^logout/$', views.logout, {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout')
]
what's wrong?
You are using your custom logout view, which does not take a next_page parameter. You have to add it as a parameter to your view and go to django logon call or just use django.contrib.auth.logout
eg. in urls.py:
from django.conf.urls import url
from django.conf import settings
from django.contrib.auth.views import logout
urlpatterns = [
url(r'^logout/$', logout, {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout')
]
Django 2.0 seems to have switched to class based view
from django.contrib.auth.views import LogoutView
url(r'^logout/$', LogoutView.as_view(), {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout'),
import django logout first, just write from django.contrib.auth import logout
at the top of your view file
For me, the "logout" url was used elsewhere, despite Django loudly complaining that it had removed the "logout" url from urls.py (I'm using Django 1.11). I have no idea why / where / how. My hacked working solution was to use a different url: "signout":
url(r'^signout/$', logout, {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout'),
For Django 2.2.x or higher, if you use path
instead url
, just import LogoutView
from django.contrib.auth.views
to urls.py
.
from django.contrib.auth.views import LogoutView
then add the following path to urlpatterns
,
path("logout/", LogoutView.as_view(), name="logout"),
Note. Must be mentioned LOGOUT_REDIRECT_URL = "my_url"
in settings.py
for redirection after logout.