Django raising 404 with a message

后端 未结 9 1191
有刺的猬
有刺的猬 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: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.

提交回复
热议问题