模板文件保存在应用程序目录下,但在呈现时会引发 TemplateDoesNotExist 异常:
模板加载器死后如下:
Django 尝试按以下顺序加载这些模板:
Using loader django.template.loaders.app_directories.Loader:
...
$PROJECT/apps/myapp/templates/search.html (File does not exist)
...
我想知道为什么它看起来:
$PROJECT/apps/myapp/templates/search.html
而不是:
$PROJECT/apps/myapp/templates/myapp/search.html
后者确实存在
$PROJECT/apps/myapp/templates/search.html
。这是它将作为doc says查找的路径。
django.template.loaders.app_directories.Loader
将按顺序在所有INSTALLED_APPS
中查找templates
目录。
django.template.loaders.filesystem.load_template_source:此加载程序根据 TEMPLATE_DIRS 从文件系统加载模板。默认情况下已启用。
django.template.loaders.app_directories.load_template_source:此加载程序从文件系统上的 Django 应用程序加载模板。对于 INSTALLED_APPS 中的每个应用程序,加载程序都会查找一个 templates 子目录。如果该目录存在,则 Django 会在其中查找模板。
这意味着您可以将模板存储在单个应用程序中,从而可以轻松地使用默认模板分发 Django 应用程序。例如,如果 INSTALLED_APPS 包含('myproject.polls','myproject.music'),则 get_template('foo.html')将按以下顺序查找模板:
/path/to/myproject/polls/templates/foo.html
/path/to/myproject/music/templates/foo.html
请注意,加载器在首次导入时会执行优化:它缓存一个列表,其中包含具有 templates 子目录的 INSTALLED_APPS 包。
默认情况下启用此加载程序。
假设你有一个默认的项目和应用程序创建为
django-admin startproject xyz
django-admin startapp abc
xyz 和 abc 文件夹都在主项目文件夹中
需要进行以下最小更改才能使第一个模板正常工作
在 settings.py 更改 INSTALLED_APPS 添加“abc”(我忘了,失败)
在 urls.py 中添加
添加行:导入 abc.views
更改 urlpatterns 以添加路径 ('abc /',abc.views.index)
在 views.py 的索引定义中使用 loader.get_template ('abc / index.html')
创建 abc / templates / abc / index.html 文件(我写了“模板”,花了几个小时才意识到这是“模板”)
确保模板和内部文件夹具有执行权限,并且 html 文件具有“其他”用户的读取权限。(我作为 root 工作,由于此错误而失败)
重新启动项目(runserver 或 apache2 服务)
总结我的错误
编辑 INSTALLED_APPS
“模板”是默认的
设置 x 和 r 权限
确保您的应用已添加到settings.py
INSTALLED_APPS
确保apps.py
中的配置名称与应用程序目录的名称相同。
class DemoConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'app' # this must be the same as the parent directory
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(69条)