
Django中出现TemplateDoesNotExist错误,通常并非配置错误,而是模板路径未遵循Django约定的“应用名/模板名”嵌套结构——模板必须置于app_name/templates/app_name/子目录下,而非直接放在app_name/templates/根目录。
django中出现templatedoesnotexist错误,通常并非配置错误,而是模板路径未遵循django约定的“应用名/模板名”嵌套结构——模板必须置于`app_name/templates/app_name/`子目录下,而非直接放在`app_name/templates/`根目录。
Django 的模板查找机制严格依赖应用级命名空间,以避免不同应用间模板名称冲突,并支持模板覆盖。即使你的 settings.py 中已正确启用 'APP_DIRS': True(默认即开启),Django 仍会按固定规则搜索模板:
- 在每个已注册应用的 templates/ 子目录中查找;
- 但要求模板文件必须位于 templates/<app_name>/ 下,而非 templates/ 根目录。
因此,针对你的项目结构:
playground/ ├── templates/ ← 此处是正确的目录 │ └── playground/ ← ✅ 必须存在此子目录 │ └── hello.html ← ✅ 模板应放在这里 ├── views.py └── ...
你当前可能将 hello.html 直接放在了 playground/templates/hello.html(即缺少 playground/ 子目录),这会导致 Django 无法匹配路径,从而抛出 TemplateDoesNotExist: playground/hello.html。
✅ 正确做法如下:
提供使用 django-unfold (v0.56+) 构建高级 Django 管理界面的专业指导。当用户提及 django-unfold、unfold admin 等内容时使用此技能。
# playground/views.py
from django.shortcuts import render
def say_hello(request):
return render(request, 'playground/hello.html') # 路径中的 'playground/' 对应 templates/playground/ 目录对应文件系统路径必须为:
playground/templates/playground/hello.html
⚠️ 注意事项:
- 确保 playground 已在 INSTALLED_APPS 中注册(如 'playground'),否则 Django 不会扫描其 templates/ 目录;
- 模板路径字符串(如 'playground/hello.html')中的前缀 playground/ 是逻辑命名空间,与磁盘路径 templates/playground/ 严格对应,不可省略;
- 若需覆盖第三方应用(如 django.contrib.admin)的模板,可新建 playground/templates/admin/base_site.html —— Django 会优先使用该路径,体现模板继承与覆盖机制。
? 小技巧:可通过 Django shell 快速验证模板是否被识别:
python manage.py shell
>>> from django.template.loader import get_template
>>> get_template('playground/hello.html')
# 若无异常则路径正确;否则会明确提示缺失路径总结:Django 的模板组织不是“扁平化”的,而是“应用隔离 + 命名空间化”的。牢记 templates/<app_name>/<template_name>.html 这一黄金路径结构,是解决绝大多数 TemplateDoesNotExist 问题的关键。

















