Debug=False 中不存在 url 的 Django 500 错误

标签 django django-urls django-errors

我在 python 3.6.7 中使用 Django 2.1.3。
假设我有这个 URL 路径:

path('admin/', admin.site.urls)

如果我导航到 /adDEBUG = True ,我看到正常的Django 404错误页面:

enter image description here

但如果我让 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 错误?

笔记:
  • 根据 docs ,如果我有 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/

    相关文章:

    django - 将 block 传递到包含的模板中而不扩展

    python - Django - URL 文件中的语法错误

    sql - django中生成的sql

    python - 为什么 django 书中的第一个 "hello world"示例不起作用?

    r - 带有 str_detect R 的多个字符串

    python - 如何使用生产数据在 Django 中运行测试(只读)?

    python - URL正则表达式帮助

    python - 如何从 Django 中的 urls.py 访问 HttpRequest

    python - 奇怪的 django 导入错误

    django - 如何强制从 django 管理命令报告错误?