[英]Django3, custom 404 page redirects to 500 when Debug=False because Django cannot find exception parameter
[英]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 將給出500
和500.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 頁面。
這與app_context
和registrations
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.