Django raising 404 with a message

2020-03-17 03:59发布

I like to raise 404 with some error message at different places in the script eg: Http404("some error msg: %s" %msg) So, in my urls.py I included:

handler404 = Custom404.as_view()

Can anyone please tell me how should I be handling the error in my views. I'm fairly new to Django, so an example would help a lot.
Many thanks in advance.

9条回答
放我归山
2楼-- · 2020-03-17 04:39

if you want to raise some sort of static messages for a particular view , you can do as follows:-

from django.http import Http404

def my_view(request):
  raise Http404("The link seems to be broken")
查看更多
We Are One
3楼-- · 2020-03-17 04:40

In my case, I wanted to take some action (e.g. logging) before returning a custom 404 page. Here is the 404 handler that does it.

def my_handler404(request, exception):
    logger.info(f'404-not-found for user {request.user} on url {request.path}')
    return HttpResponseNotFound(render(request, "shared/404.html"))

Note that HttpResponseNotFound is required. Otherwise, the response's HTTP status code is 200.

查看更多
beautiful°
4楼-- · 2020-03-17 04:46

I figured out a solution for Django 2.2 (2019) after a lot of the middleware changed. It is very similar to Muhammed's answer from 2013. So here it is:

middleware.py

from django.http import Http404, HttpResponse

class CustomHTTP404Middleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before the view (and later middleware) are called.
        response = self.get_response(request)
        # Code to be executed for each request/response after the view is called.
        return response

    def process_exception(self, request, exception):
        if isinstance(exception, Http404):
            message = f"""
                {exception.args},
                User: {request.user},
                Referrer: {request.META.get('HTTP_REFERRER', 'no referrer')}
            """
            exception.args = (message,)

Also, add this last to your middleware in settings.py: 'app.middleware.http404.CustomHTTP404Middleware',

查看更多
登录 后发表回答