如何在Django中正确设置自定义handler404? [英] How to properly setup custom handler404 in django?

查看:106
本文介绍了如何在Django中正确设置自定义handler404?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档应该非常简单:我只需要定义 handler404 .目前,我正在顶部 urls.py :

According to the documentation this should be fairly simple: I just need to define handler404. Currently I am doing, in my top urls.py:

urlpatterns = [
    ...
]

handler404 = 'myapp.views.handle_page_not_found'

该应用程序已安装.相应的视图就是(暂时(我只是想在404情况下重定向到首页)):

The application is installed. The corresponding view is just (for the time being I just want to redirect to the homepage in case of 404):

def handle_page_not_found(request):
    return redirect('homepage')

但这没有作用:显示标准(调试) 404 页面.

But this has no effect: the standard (debug) 404 page is shown.

文档有点含糊:

  • 应该在哪里定义 handler404 ?该文档在 URLconf 中说,但是,到底在哪里?我有几个应用程序,每个应用程序都有不同的 urls.py .我可以把它们放进去吗?在顶部的 URLconf 中?为什么?在哪里记录?
  • 此处理程序将捕获什么?它会捕获 django.http.Http404 django.http.HttpResponseNotFound django.http.HttpResponse (带有 status = 404 )?
  • where should handler404 be defined? The documentation says in the URLconf but, where exactly? I have several applications, each with a different urls.py. Can I put it in any of them? In the top URLconf? Why? Where is this documented?
  • what will be catched by this handler? Will it catch django.http.Http404, django.http.HttpResponseNotFound, django.http.HttpResponse (with status=404)?

推荐答案

正如我们所讨论的,您的设置是正确的,但是在settings.py中,您应该将 DEBUG = False 设置为.它更多的是生产功能,并且不能在开发环境中工作(除非您在开发机中当然有 DEBUG = False ).

As we discussed, your setup is correct, but in settings.py you should make DEBUG=False. It's more of a production feature and won't work in development environment(unless you have DEBUG=False in dev machine of course).

这篇关于如何在Django中正确设置自定义handler404?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆