Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hacking Django Admin, hooks for login/logout

How do I add hooks to the Django Admin, such that I can execute a function when the user logs in or out?

like image 571
fadedbee Avatar asked Jun 14 '10 13:06

fadedbee


Video Answer


1 Answers

Django does sadly not send any signals on that events.... But you could make your own custom AuthorizationBackend that enables you to do so:

from django.dispatch import Signal

post_login = Signal(providing_args=['user'])

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User

class AuthSignalBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        try:
            user = User.objects.get(username=username)
            if user.check_password(password):
                post_login.send(sender=None, user=user)
                return user
        except User.DoesNotExist:
            return None


def login_handler(sender, **kwargs):
    print "logging in..."        
post_login.connect(login_handler)

To enable it you have to put AUTHENTICATION_BACKENDS = (myapp.mymodule.AuthSignalBackend',) in your settings.py!

like image 174
Bernhard Vallant Avatar answered Sep 28 '22 00:09

Bernhard Vallant