【问题标题】:Django 1.10 404.html template not found找不到 Django 1.10 404.html 模板
【发布时间】:2016-10-29 10:21:27
【问题描述】:

据我在 Django 文档中看到的,要显示自定义 404 页面,您只需将 404.html 放在根模板目录中即可。

所以我的项目结构是:

django_project
|_ config
| |_ settings.py
| |_ urls.py
|
|_ templates
  |_ base.html
  |_ index.html
  |_ 404.html

在 settings.py 我有以下模板设置:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ["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',
                'contact.views.contact_info',
            ],
        },
    },
]

对于'DIRS' 参数,我也使用了os.path.join(BASE_DIR, "templates")。这具有完全相同的结果。

我也用过

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, "templates"), 
)

这会导致弃用警告。

在 urls.py 中我也没有做任何特别的事情:

from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView

urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name="index.html"), name="index"),

    url(r'^admin/', admin.site.urls),
]

模板继承在其他应用程序中完美运行,因此找到了模板目录。

在设置中:DEBUG=False

当我输入错误的 url 时,我会得到 Django 默认的“未找到”页面。

我在这里错过了什么?

【问题讨论】:

  • 嗯,缺少的一件事是对实际问题的任何描述。会发生什么?

标签: python django


【解决方案1】:

您需要覆盖“handler404”变量,将其添加到 urls.py

from django.conf.urls import handler404

handler404 = 'your_app.views.404'

https://docs.djangoproject.com/en/1.10/topics/http/views/#customizing-error-views

【讨论】:

    【解决方案2】:

    我猜你必须为你的 404.html 模板指定路由,或者使用 django 快捷方式 'get_object_or_404' 来处理错误 404。

    【讨论】:

      猜你喜欢
      • 2017-02-11
      • 1970-01-01
      • 2013-06-27
      • 1970-01-01
      • 2018-01-02
      • 2012-07-10
      • 2015-03-14
      • 2020-05-27
      相关资源
      最近更新 更多