Django raising 404 with a message

后端 未结 9 1060
有刺的猬
有刺的猬 2020-12-19 05:31

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:

<         


        
相关标签:
9条回答
  • 2020-12-19 06:09

    In general, 404 error is "page not found" error - it should not have customizable messages, simply because it should be raised only when a page is not found.

    You can return a TemplateResponse with status parameter set to 404

    0 讨论(0)
  • 2020-12-19 06:13

    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")
    
    0 讨论(0)
  • 2020-12-19 06:18

    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',

    0 讨论(0)
  • 2020-12-19 06:23

    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.

    0 讨论(0)
  • 2020-12-19 06:25

    Raise an Http404 exception inside a view. It's usually done when you catch a DoesNotExist exception. For example:

    from django.http import Http404
    
    def article_view(request, slug):
        try:
            entry = Article.objects.get(slug=slug)
        except Article.DoesNotExist:
            raise Http404()
        return render(request, 'news/article.html', {'article': entry, })
    

    Even better, use get_object_or_404 shortcut:

    from django.shortcuts import get_object_or_404
    
    def article_view(request):
        article = get_object_or_404(MyModel, pk=1)
        return render(request, 'news/article.html', {'article': entry, })
    

    If you'd like to customize the default 404 Page not found response, put your own template called 404.html to the templates folder.

    0 讨论(0)
  • 2020-12-19 06:25

    Yes we can show specific exception message when raise Http404.

    Pass some exception message like this

    raise Http404('Any kind of message ')
    

    Add 404.html page into templates directory.

    templates/404.html

    {{exception}}
    
    0 讨论(0)
提交回复
热议问题