Django引入模板报错TemplateDoesNotExist,如何正确include模板?
Django中正确引入模板的方法
你遇到的TemplateDoesNotExist错误,是因为模板路径写法不符合Django的模板查找规则。Django会根据settings.py里的TEMPLATES配置自动查找模板目录,不需要写完整的绝对路径前缀。
正确写法分两种情况:
情况1:header.html在hospital app的
templates/hospital/目录下(推荐规范结构)
直接写带app名的相对路径,避免不同app间模板重名冲突:{% if request.path != '/login/' %} {% include "hospital/header.html" %} {% endif %}情况2:header.html在项目根目录的
templates/目录下
先确保settings.py的TEMPLATES配置中,DIRS包含根模板目录(BASE_DIR / 'templates'),然后直接写模板文件名:{% if request.path != '/login/' %} {% include "header.html" %} {% endif %}
补充settings.py的TEMPLATES配置要点:
要让Django正确找到模板,需保证以下核心配置:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], # 若使用根目录模板需添加此项 'APP_DIRS': True, # 开启自动查找已注册app内的templates目录 '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', ], }, }, ]
内容的提问来源于stack exchange,提问作者abu abu
相关产品推荐
相关产品推荐

