Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django override auth_views.logout

I'm trying to figure out how I can override the auth_views.logout method. Normally I wouldn't have a problem doing this with regard to overriding class methods, however I've realised I'm trying override a view, is this possible to do in Django?

The reason why I want to override the view is so I can include a message via messages.add_message that says 'You are signed out'. Initially it was redirecting to a logout template, however I wanted to make it so when somebody logs out it redirects to the login page, I am currently doing this via next_page in auth.urls.py

Thanks

like image 263
Imran Azad Avatar asked Jan 24 '12 19:01

Imran Azad


2 Answers

def my_logout(request):
     # message user or whatever
     return auth_views.logout(request)

Then, hook up my_logout in your urls.py instead of the default auth_views.logout. (Of course you can change the name of the view to whatever).

like image 84
Chris Pratt Avatar answered Sep 19 '22 14:09

Chris Pratt


Oops, I just re-read the part where you say you need to do a redirect. Chris's answer will be able to handle redirection.


For django 1.3, there is a logout signal which is documented specifically for this purpose.

The auth framework uses two signals that can be used for notification when a user logs in or out.

https://docs.djangoproject.com/en/dev/topics/auth/#login-and-logout-signals

from django.contrib.auth.signals import user_logged_out

def logout_notifier(sender, request, user, **kwargs):
    messages.add_message(request, 'Thanks for logging out!')

user_logged_out.connect(logout_notifier)
like image 31
Yuji 'Tomita' Tomita Avatar answered Sep 20 '22 14:09

Yuji 'Tomita' Tomita