我在 python 3.6.7 中使用 Django 2.1.3。
假设我有这个 URL 路径:
path('admin/', admin.site.urls)
如果我导航到
/ad
而DEBUG = True
,我看到正常的Django 404错误页面:但如果我让
DEBUG = False
然后服务器显示 500.htm 给我而不是 404.html 对于无效的 URL /ad
(不匹配任何 URL 模式)。404.html 正在显示引发 404 错误的有效 URL。 (就像 不存在的对象 查询发生在
get_object_or_404
函数中)这是我的
/templates
目录结构:/templates
400.html
403.html
404.html
500.html
index.html
...
那么,如果请求 URL 不匹配任何 URL 模式,我应该如何告诉 Django 在生产中(除了开发之外)显示 404 错误?
笔记:
404.html
在根模板目录中,此 404.html 将与默认错误处理程序一起使用。 更新:
我发现这是因为
defaults.page_not_found
引发 Resolver404
,这是由:the path passed to resolve() doesn’t map to a view
这正是发生的事情,(
/ad
不匹配任何 View )这是我的 urls.py:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
最佳答案
我发现我的一个自定义模板上下文处理器使用 django.urls.resolve
由于路径不匹配任何 View ,resolve
加薪 解析器404 .
所以我修复了上下文处理器,问题解决了!
关于Debug=False 中不存在 url 的 Django 500 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54062209/