Search code examples
pythondjangodjango-views

In production bad url shows Internal Server Error instead of customized 404


I have created a simple handler404 according to documentation. In local it works fine, for example when user tries to access an url that does not exist the handler of 404 error is called. But in production it shows a classic "Internal Server Error" and I can't understand why.

The handler are these:

view.py:

def handler500(request):
    context = {}
    return render(request, "maintenance/error500.html", status=500)


def handler404(request, exception):
    context = {}
    return render(request, "maintenance/error404.html", status=404)

EDIT: From log a I have obtain this, what is the meaning?

GET /session/987567865850/ HTTP/1.1" 500 141 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:92.0) Gecko/20100101 Firefox/92.0

Solution

  • Moved from an edit to the question by the OP to an answer.

    Create a middleware class that handles the 404 exception:

    class Custom404Middleware(object):
    
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            return self.get_response(request)
    
        def process_exception(self, request, exception):
            if isinstance(exception, Http404):
                return render(request, "maintenance/error404.html", status=404)