Imran Azad
Imran Azad

Reputation: 1404

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

Upvotes: 6

Views: 5148

Answers (3)

nicorellius
nicorellius

Reputation: 4053

You can use @Chris Pratt's idea as CBV, and then hook up in your URLConf:

views.py

from django.contrib.auth import logout    

class LogoutView(View):

    template_name = 'registration/logged_out.html'

    def get(self, request):
        response = logout(request)

        return render(response, self.template_name)

urls.py

urlpatterns = [
    . . .
    url(r'^logout/$', LogoutView.as_view(), name='logout')
    . . .
]

Upvotes: 0

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)

Upvotes: 2

Chris Pratt
Chris Pratt

Reputation: 239430

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).

Upvotes: 6

Related Questions