根据 Django Docs , 模板加载器将
load templates from Django apps on the filesystem. For each app in INSTALLED_APPS, the loader looks for a templates subdirectory.
进行中:
...then get_template('foo.html') will look for foo.html in these directories, in this order:
/path/to/myproject/polls/templates/
/path/to/myproject/music/templates/
所以...在我的“网站”项目中,我有一个“www”应用程序。所以目录结构是/path/to/project/website/www/
我在“www”中创建了一个“templates”目录,并将“page_list.html”(/path/to/project/website/www/page_list.html)
该应用程序列在“INSTALLED_APPS”中,但是当我尝试在 urls.py 中执行此操作时:
url('^$', ListView.as_view(model=Page,))
我收到“TemplateDoesNotExist”,错误提示 django.template.loaders.app_directories.Loader 正在寻找“/path/to/project/website/templates/www/page_list.html"或 /path/to/project/website/www/templates/www/page_list.html
如果我将模板放在 website/www/templates/www 中,它就可以工作...但我想知道为什么它会这样工作。在 app 文件夹中有一个 templates 文件夹,然后在 templates 目录中有另一个名为 application 的文件夹似乎很荒谬....
并且文档说它应该在 project/app/templates 内部查看... 我有
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
虽然 app_directories.Loader 的文档没有说您需要它(并且还尝试删除该选项)。
这是怎么回事?我做错了什么吗?是关于通用 View 的问题,还是还有其他问题?
请您参考如下方法:
您的问题是 Django 的基于通用类的 View 的自动模板命名。如果你使用 django.views.generic.ListView 你会得到 MultipleObjectTemplateResponseMixin这将创建您的模板名称 www/poll_list.html。此名称与 app_directory Loader 生成的前缀相结合所以你得到了 /path/to/project/app/templates/www/poll_list.html。
如果你不想要这个,你有不同的选择(按此顺序):
- 在您的 View 中使用 template_name 参数或属性。
- 子类化 MultipleObjectTemplateResponseMixin 并去除应用程序前缀。然后将其混合到您的 View 中。
- 不要使用 app_directory 加载器。
