【问题标题】:Django: Strange TemplateDoesNotExist errorDjango:奇怪的 TemplateDoesNotExist 错误
【发布时间】:2014-05-27 01:32:07
【问题描述】:

我在 Django 1.6.2 上收到 "TemplateDoesNotExist at /" 错误。 Stackoverflow 多次介绍过,但到目前为止没有任何效果。

模板是它们自己文件夹的一部分,不存储在应用程序中。

manage.py
project_dir
|_ settings.py
|_ urls.py
|_ apps
    \_ app1
        \_ views.py
        |_ urls.py
        |_ models.py
|_ templates
    \_ base.html
    \_ pages
         \_ index.html

我已将TEMPLATE_DIRTEMPLATE_LOADERS 设置如下:

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(os.path.join(BASE_DIR, 'project/apps/'))
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'project/templates/'),
)
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

当我打印文件夹TEMPLATE_DIRSBASE_DIR 时,它们完全没问题。 当我复制TEMPLATE_DIRS的打印输出,直接在浏览器中查看,就可以查看模板了。

我注意到一个奇怪的事情是加载程序django.template.loaders.filesystem.Loader 没有在错误消息中列出任何文件夹。 django.template.loaders.app_directories.Loader 列出了一些与应用程序相关的文件夹。

模板通过urls.py调用

from django.views.generic.base import TemplateView
...
urlpatterns = patterns('',
    url(r'^$', TemplateView.as_view(template_name='app1/index.html'), name='index'),
    ...
) 

模板报错的原因是什么?

【问题讨论】:

    标签: python django templates django-templates


    【解决方案1】:

    我在文件结构中看不到任何“app1/index.html”。

    根据提供的内容,应该是

    url(r'^$', TemplateView.as_view(template_name='pages/index.html'), name='index'),
    

    【讨论】:

    • 我改变了路径 - 没有成功。现在我已经设置了模板的绝对路径,我可以在浏览器中查看,但 Django 仍然抱怨该文件存在。是否有我忘记设置的文件权限?
    【解决方案2】:

    天哪,这个错误太可悲了!我刚刚重新阅读了我的settings.py,发现TEMPLATE_DIRS 有第二个定义。这覆盖了所有设置的目录,并解释了为什么 django.template.loaders.app_directories.Loader 为空。

    【讨论】:

      【解决方案3】:

      你能补充几句吗?我想看看你的整个目录设置,包括你的settings.py 在哪里。我担心您的BASE_DIRTEMPLATE_DIRS 是错误的。我认为 TEMPLATE_DIRS 只是 'templates' 而不是 'project/templates' 但它可以与您的设置一起使用。

      如果不是这样,您能否发布您的views.py 和您尝试调用的模板代码?

      【讨论】:

      • 我已经扩展了文件夹描述。我希望它能提供更多的见解。感谢您的回复。
      猜你喜欢
      • 2014-02-19
      • 2013-06-20
      • 2015-09-02
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2011-07-18
      相关资源
      最近更新 更多