
django中出现templatedoesnotexist错误,通常并非配置错误,而是模板路径未遵循“app_name/template_name.html”的约定;正确做法是将模板置于app目录下的templates/app_name/子目录中。
django中出现templatedoesnotexist错误,通常并非配置错误,而是模板路径未遵循“app_name/template_name.html”的约定;正确做法是将模板置于app目录下的templates/app_name/子目录中。
在Django中,APP_DIRS=True(默认启用)意味着Django会自动在每个已注册应用(INSTALLED_APPS中列出)的 templates/ 子目录下查找模板,但关键前提是:模板必须位于 templates/
以你的项目结构为例:
playground/ ├── templates/ ← 正确位置:此处必须是 templates/ │ └── playground/ ← 必须包含与应用同名的子目录 │ └── hello.html ← 模板文件最终存放于此 ├── views.py └── apps.py
因此,render(request, 'playground/hello.html') 的查找逻辑是:
- Django遍历 INSTALLED_APPS 中每个app(如 'playground');
- 在该app目录内搜索 templates/ 文件夹;
- 进入 templates/ 后,按传入的路径 'playground/hello.html' 逐级匹配:先找 playground/ 子目录,再找其中的 hello.html。
✅ 正确路径:playground/templates/playground/hello.html
❌ 错误路径:playground/templates/hello.html(缺少 playground/ 子目录)或 playground/hello.html(无templates层级)
验证步骤
- 确保 playground 已添加至 settings.py 的 INSTALLED_APPS:
INSTALLED_APPS = [ # ... 其他app 'playground', # 必须存在且拼写准确 ] - 创建标准模板路径:
mkdir -p playground/templates/playground touch playground/templates/playground/hello.html
- 在 hello.html 中添加简单内容便于测试:
<h1>Hello from Playground!</h1>
补充说明:为什么需要重复应用名?
这种设计支持模板继承与覆盖:
- 多个app可提供同名模板(如 registration/login.html),Django按 INSTALLED_APPS 顺序优先使用靠前app中的版本;
- 第三方app(如 django.contrib.admin)的模板也可被本地app覆盖:只需在 playground/templates/admin/base_site.html 中定义即可替换后台管理界面。
常见陷阱提醒
- ❌ 模板文件名含大写字母或特殊符号(如 Hello.html)——推荐全小写+下划线;
- ❌ TEMPLATES['DIRS'] 中手动添加了自定义路径但未包含 playground/templates ——若需全局模板目录,应显式加入;
- ❌ 使用 os.path.join(BASE_DIR, 'templates') 时路径拼写错误或未在 DIRS 中配置;
- ✅ 开发阶段建议开启 DEBUG=True,Django错误页会明确列出所有已搜索的模板路径,便于快速定位缺失位置。
遵循“templates/











