Home > OS >  Django middleware runs twice because of request to jsi18n
Django middleware runs twice because of request to jsi18n

Time:03-17

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?

CodePudding user response:

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)
  • Related