How to run a python function on every Admin page load in Django
django, django-admin, python, python-3.x
Solution
Disclaimer: I don't know a terrible lot about the internals or API(s) of Django perse.
What you need to use/write is a Middleware Component.
See: Django Middleware
Trivial Example:
class LocaleMiddleware(object):
def process_request(self, request):
if 'locale' in request.cookies:
request.locale = request.cookies.locale
else:
request.locale = None
def process_response(self, request, response):
if getattr(request, 'locale', False):
response.cookies['locale'] = request.locale
See also: Understanding Django Middleware from Effective Django.
Problem
I would like a python function to be run any time a page from the admin interface is loaded. This does not need to run on every page load(ie non-admin related pages). This function requires the request object or the user id. I know I could create a new view and call it from javascript from the page, but this seems like a horrible way of doing it. Is there a way to somehow attach a function to admin page loads server side without adding any additional dependencies? Update: the function is used to hook into a kind of logging system that keeps track of first/last interaction of each user each day that needs to be updated whenever the user uses the admin interface. It would seem that a middleware app would allow me to do what I want to do, thank you guys!