'How to logout in 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?

enter image description here



Solution 1:[1]

You are using your custom logout view which doesn't take next_page parameter. You should add it as parameter to your view and pass to django logout call, or just use django.contrib.auth.logout

e.g. 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')
]

Solution 2:[2]

Django 2.0 it looks like it switched to a class based view

from django.contrib.auth.views import LogoutView

url(r'^logout/$', LogoutView.as_view(), {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout'),

Solution 3:[3]

For Django 2.2.x or higher, if you are using path instead of url, then simply import LogoutView from django.contrib.auth.views in urls.py.

from django.contrib.auth.views import LogoutView

then add following path in urlpatterns,

path("logout/", LogoutView.as_view(), name="logout"),

Note: You need to mention LOGOUT_REDIRECT_URL = "my_url" in settings.py for redirection after logout.

Solution 4:[4]

import django logout first , just write from django.contrib.auth import logout at the top of your view file

Solution 5:[5]

For me, the url 'logout' was being used elsewhere, despite Django loudly complaining if I removed the 'logout' url from urls.py (I am using Django 1.11). I have no idea why/where/how. My hacky working solution was to use a different url, 'signout':

    url(r'^signout/$', logout, {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout'),

Solution 6:[6]

The following works on Django 4:

from django.urls import path

path("logout/", LogoutView.as_view(template_name="template_to_redirect.html"), name="logout")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 bruinlax
Solution 3 khaldi
Solution 4 Shakhawat Hossain
Solution 5
Solution 6 Stas Oknedis