Django无法找到引用模板问题求助:已配置INSTALLED_APPS与DjangoTemplates
Django模板include找不到文件的解决方案
1. 修正include语句的模板名写法
你的include语句缺少引号,Django会把othermodels.html当成变量解析,直接导致"没有提供模板名"的错误。正确写法如下:
{% for model_othermodel in model.othermodels.all%} {% include "othermodels.html" with othermodel=model_othermodel %} {% endfor %}
如果othermodels.html放在应用模板的子目录(比如templates/django_app/),建议使用带应用前缀的路径避免模板名冲突:
{% include "django_app/othermodels.html" with othermodel=model_othermodel %}
2. 修复TEMPLATES配置
正确设置DIRS路径
确保DIRS指向正确的模板目录,BASE_DIR是项目根目录(root/),根据settings.py的位置调整:
如果settings在root/django_project/下,BASE_DIR配置应为:
from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # 此时指向root/目录 DIRS = [BASE_DIR / 'django_app' / 'templates']
或者使用os.path写法:
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DIRS = [os.path.join(BASE_DIR, 'django_app', 'templates')]
开启APP_DIRS
确保TEMPLATES配置中APP_DIRS = True,这样Django会自动检索INSTALLED_APPS中每个应用的templates目录:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'django_app' / 'templates'], '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', ], }, }, ]
3. 确认INSTALLED_APPS配置
把本地应用django_app添加到INSTALLED_APPS,放在Django官方应用之后即可:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_app', # 添加你的应用 ]
不要将其移至首位,避免触发admin和模型注册的冲突。
4. 验证模板文件位置
确保othermodels.html存在于root/django_app/templates/(或root/django_app/templates/django_app/)目录下,文件名和后缀完全匹配(注意Linux/macOS系统区分大小写)。
内容的提问来源于stack exchange,提问作者Crazi_Ninja
相关产品推荐
相关产品推荐

