Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a python function on every Admin page load in Django

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!

like image 514
pfc Avatar asked Sep 12 '25 05:09

pfc


2 Answers

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.

like image 98
James Mills Avatar answered Sep 13 '25 19:09

James Mills


One way would be to create a middleware and check on every page request if it is an admin page:

https://docs.djangoproject.com/en/dev/topics/http/middleware/

like image 24
dm03514 Avatar answered Sep 13 '25 18:09

dm03514