当debug为false时,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/",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)时,如果DEBUG = True给出一个适当的404

如果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")]
kkkkkwwwpopo 回答:当debug为false时,Django为未知URL提供500而不是404

这与app_contextregistrations context_processors有关。

在那些他们使用request并针对它解决问题(即resolve(request.path).app_name)的情况下,它们永远不会因404或其他错误而匹配-从而导致{{1} }响应错误。

现在,我已经将这两个函数中的每个函数包装在自己的简单if语句中:

500

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

,

当DEBUG = True时,Django会渲染调试页面,而忽略404页面。

请参见Show 404 page on django when DEBUG=True

本文链接:https://www.f2er.com/3164474.html

大家都在问