簡體   English   中英

當調試為假時,Django 為未知 URL 提供 500 而不是 404

[英]Django giving 500 instead of 404 for unknown URLs when debug is false

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...

When I python manage.py runserver and I hit a URL I know doesn't exist (like http://project/randomtrash.php ) it gives an appropriate 404 if 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")]

Django 在 DEBUG=True 時渲染調試頁面,忽略 404 頁面。

當 DEBUG=True 時,請參閱 django 上的顯示 404 頁面

這與app_contextregistrations context_processors 有關。

在那些他們使用request並針對它解決問題(即resolve(request.path).app_name )中,這將永遠不會匹配404或其他錯誤 - 從而導致500錯誤響應。

我現在已經將這兩個函數中的每一個都包含在它自己的簡單 if 語句中:

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

現在所有錯誤都按預期正確呈現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM