0

Running an extremely simple piece of middleware on django 3.2, I display notifications to users before every page loads. The code to do this looks like his:

from django.contrib import messages
class ChangeNotifierMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        
    def __call__(self, request):
        messages.add_message(request, messages.INFO,"test")
        response = self.get_response(request)

The issue however, is just like in Django: custom middleware called twice, this middleware is executed twice per request. This only happens in the django admin interface, and not because of requests to the favicon, but because of requests to /admin/jsi18n/. That makes the cause for this issue different (I did not specify any urls for jsi18n anywhere)

The result of all this is that on the front-end of my side, i get a single notification saying "test", as it should be. On the backend/admin interface, I get two notifications saying "test". How can i make django middleware run only once before a page loads, is there a way to guarantee the code only runs once?

Vancha
  • 63
  • 1
  • 8

1 Answers1

0

It looks like jsi18n is supposed to present the proper language translations for javascript activities.

You can skip adding your message for all urls containing "jsi18n" if "jsi18n" not in request.path

from django.contrib import messages
class ChangeNotifierMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        
    def __call__(self, request):
        if "jsi18n" not in request.path:
            messages.add_message(request, messages.INFO,"test")
        response = self.get_response(request)
Jimmy Pells
  • 674
  • 1
  • 5
  • 12
  • Thank you for your answer. This is what I came up with in the mean time as well, but i figured it would still be called when I install something that does perform additional request. If jsi18n gets called, are there other django features that, when enabled, perform additional requests? If so, i will have to add all those urls into a list and check against them manually. Untill a more robust solution exists, I'll use exactly your idea, thanks again! – Vancha Mar 16 '22 at 12:48
  • Unfortunately, I don't use Django's pre-built admin so I am unfamiliar with its features. Instead of trying to customize Django's pre-built admin, I tend to build my own custom back-end for applications. – Jimmy Pells Mar 16 '22 at 12:53