簡體   English   中英

渲染模板位於Django中的未注冊文件夾中

[英]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_DIRSTEMPLATES

我需要使用在/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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM