![](/img/trans.png)
[英]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.