首页 > 解决方案 > 当调试为假时,Django 为未知 URL 提供 500 而不是 404

问题描述

Django = 2.1.x

Python = 3.7.x

如果 Debug 为 True - 它返回 404。

如果 Debug 为 False - 它会给出 500 错误。

我的project.urls文件如下所示:

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", app1.views.log_in, name="log_in"),
    path("log_in/", app1.views.log_in, name="log_in"),
    path("logout/", app1.views.log_out, name="logout"),
    path("launcher/", app1.views.launcher, name="launcher"),
    path("app2/", include("app2.urls")),
    path("app3/", include("app3.urls")),
]

我的目录结构如下所示:

Project_directory
    static_directory
        ...js files and css files and such...
    templates_directory
        400.html
        403.html
        404.html
        500.html
        base.html (all apps extend this page, which works great)
    project_directory
        urls.py
        settings.py
        ...other files...
    app1_directory
        views.py
        models.py
        templates_directory
            app1
                ...template files...
        ...other app1 files/directories...
    app2_directory
        ...app2 directories and files...
    app3_directory
        ...app3 directories and files...

当我python manage.py runserver和我点击一个我知道不存在的 URL(如http://project/randomtrash.php)时,它会给出适当的 404,如果DEBUG = True

如果DEBUG = False然后点击相同的 URL 将给出一个500500.html显示。

我的重要部分settings.py看起来像这样:

# These two settings are only for testing purposes and are different
# In production
DEBUG = False
ALLOWED_HOSTS = ["*"]

ROOT_URLCONF = "project.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        # DIRS lets the apps extend base.html
        "DIRS": [os.path.join(BASE_DIR, "templates")],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                "project.context_processors.app_context",
                "project.context_processors.registrations",
            ]
        },
    }
]

STATIC_URL = "/static/"

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")

SESSION_EXPIRE_AT_BROWSER_CLOSE = True

if DEBUG:
    STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]

标签: pythondjangodjango-templateshttp-status-code-404

解决方案


app_contextregistrations上下文处理器有关。

在那些他们正在使用request并解决它的事情(即resolve(request.path).app_name)中,这些事情永远不会匹配一个404或其他错误 - 从而导致500响应错误。

我现在已经将这两个函数中的每一个都包含在它自己的简单 if 语句中:

if request.resolver_match:
    ...do stuff...

现在所有错误都按预期正确呈现。


推荐阅读