[英]render_template() cannot find template located in blueprint folder
[英]Render template located in a unregistered folder in Django
在我的网站上,我在特定文件夹中有demo
模板:
project_root
├── project
│ ├── design # templates
│ │ ├── demo # template folder
│ │ │ └── index.html # template file
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── some_app
│ └── ...
└── manage.py
我试图使用TemplateView
从特定的URL呈现我的demo/index.html
,但是Django无法找到我的模板,即使我将/project/design
添加到TEMPLATE_DIRS
或TEMPLATES
。
我需要使用在/project/design
文件夹中具有模板的demo/index.html
字符串来呈现模板。 我怎么做?
在您使用的正确模板引擎中添加此目录,例如DjangoTemplate 。
例如( settings.py
文件):
from unipath import Path
BASE_DIR = Path(__file__).ancestor(2)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR + '/project/design/',
],
'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',
],
},
},
]
检查BASE_DIR
变量是否对应于包含所有应用程序的文件夹。
之后,使用以下代码租用您的模板:
return render(request, 'demo/index.html')
最佳实践 :将模板放在每个应用程序的project_root/templates/<app_name>/
或templates/<app_name>
文件夹中。
阅读有关模板的更多信息: Django-模板
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.