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?
source to share
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')
]
source to share
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'),
source to share
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.
source to share