python - 当调试为假时,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 将给出一个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")]
解决方案
这app_context
与registrations
上下文处理器有关。
在那些他们正在使用request
并解决它的事情(即resolve(request.path).app_name
)中,这些事情永远不会匹配一个404
或其他错误 - 从而导致500
响应错误。
我现在已经将这两个函数中的每一个都包含在它自己的简单 if 语句中:
if request.resolver_match:
...do stuff...
现在所有错误都按预期正确呈现。
推荐阅读
- lua - 如何在 lua 中随机化文件根目录?
- python - Python Pandas,用目录路径替换列的每一行中的文件路径?
- css - 如何使用 CSS 选择器在 h4 之后更改字体大小?
- c++ - 如何从文件中获取图标,然后将其设置为创建的快捷方式?
- php-5.6 - 管理员中的 Magento 1 错误 404
- javascript - 如何在 Javascript 中获取前三个创建的元素?
- css - 使用 SVG 的 CSS 背景不会在 Chrome 中显示
- javascript - Three.js 在动态 Angular 组件中渲染
- tensorflow - Tensorflow Keras 模型和估计器有什么区别?
- python-3.x - 上传带有请求的文件