Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to logout in django?

Tags:

python

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

like image 691
Nursultan Kenzhegaliyev Avatar asked Mar 28 '17 12:03

Nursultan Kenzhegaliyev


3 Answers

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.

like image 99
khaldi Avatar answered Oct 12 '22 18:10

khaldi


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'),
like image 21
bruinlax Avatar answered Oct 12 '22 20:10

bruinlax


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

like image 45
Shakhawat Hossain Avatar answered Oct 12 '22 19:10

Shakhawat Hossain