How do I add hooks to the Django Admin, such that I can execute a function when the user logs in or out?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Django __str__ returned non-string (type NoneType)
- Evil ctypes hack in python
Update: This method is obsolete since Django 1.3, see Tommy's answer below for using signals.
I was also looking for an answer to this and ended up going another way. You can use your own views for login and logout, which perform some action and then call the auth views. For login:
And for logout:
You can do whatever processing you like in your custom views in place of the do_something placeholders, such as emitting signals, logging log-in and log-out times, etc.
Finally, don't forget to update your
urls.py
to point to your custom views.I'm not sure how a custom auth backend can handle logout events, as i eventually gave up on that and tried this instead. Additionally, this approach has the advantage of making available the
request
object instead of just the user.Django does sadly not send any signals on that events.... But you could make your own custom AuthorizationBackend that enables you to do so:
To enable it you have to put
AUTHENTICATION_BACKENDS = (myapp.mymodule.AuthSignalBackend',)
in your settings.py!As of Django 1.3, the auth framework does generate signals for login and logout which can be used to provide your own hook.
You have to connect your function to the django.contrib.auth.signals.user_logged_in signal like:
I just found this thread when searching for a solution so others might too...
Lazerscience answer looks good so far but I also notice that the Django core devs have accepted a patch that will cause a Signal on log-in/log-out.
This might be a more elegant solution once it makes it into an official Django release.
And for reference, the docs on Signals.