CommonMiddleware is not working in other (custom) middlewares

CommonMiddleware not working in custom middlewares

I have a custom middleware like below:

class PageNotFoundMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        sura_pattern = r"/sura/[1-9]\d*-[1-9]\d*/$"

        print(f'\n\n{request.path_info}: {response.status_code}\n\n')  # <--

        if response.status_code == 404:
            if re.match(sura_pattern, request.path_info):
                return response
            return render(request, '404.html')
        elif response.status_code == 400:
            return render(request, '400.html')
        elif response.status_code == 500:
            return render(request, '500.html')
        elif response.status_code == 200 or response.status_code == 301:
            return response

In the line I marked with arrow: “<–”, the request.path_ifo, has no ending “/”.


If the inputted url is: /sura/10, then it shows me /sura/10, but it must append and ending “/” to it. this url is valid, here is the

urlpatterns = [
    path("", home, name="home"),

    path('sura/<int:sura>/', sura_handler, name='sura_handler'),  # <-- path which should get the url
    path('sura/<str:sura_aya>/', index, name='index'),
    path('page/<str:page>/', page_handler, name='page_handler'),
    path('juz/<str:juz>/', juz_handler, name='juz_handler'),

    path('api/', include('quran.api.urls')),

    path('sw/', sw, name="sw"),
    path('manifest/', manifest, name="manifest"),


Before regex executed, the response.status_code is 404. While if I correctly input the url, (like this: /sura/10/) then the response.status_code in not 404.

can someone help me please find out why CommonMiddleware doesn’t work in custom middlewares?

Middlewares in django:


    'quran.middleware.PageNotFoundMiddleware'  # <-- custom middleware

django version: 4.2

I tried to validate the url in my custom middleware using regex.

I just find out that the CommonMiddleware is not working in custom middlewares in django.

django version: 4.2

here is stackoverflow question link:

The regex you defined does not match on what you expect it to match.

It will not match /sura/10/.