[Django]-Proper way to add code to logout view in Django

6👍

You’re calling the wrong logout.

from django.contrib.auth import logout

should be

from django.contrib.auth.views import logout

1👍

You should import logout from views, from django.contrib.auth.views import logout, instead of from django.contrib.auth import logout.

On side note, for such behavior you may want to use logout signal. Refer login logout signals

👤Rohan

0👍

I got the same problem as you and used this simple workaround:

views.py:

def my_logout(request):
    # Staff you want to do before logout
    from django.http import HttpResponseRedirect
    return HttpResponseRedirect("/logout2/")

urls.py:

(r'^logout/$', 'views.my_logout'),
url(r'^logout2/$',
    django.contrib.auth.views.logout,
    {'template_name': 'logged_out.html'},  # Next page
    name='auth_logout'),
👤Meilo

0👍

This has become a problem with the Django V2. You could define your login and logout functions in views and call them in the urls. Or you can follow the example given in the Django Documentation

from django.contrib.auth import views as auth_views

path(‘accounts/login/’, auth_views.LoginView.as_view()),

Leave a comment