Django查找templates的原理
已于 2025年08月05日 17:15 修改
访问次数:0
✅ Django 模板查找原理总结
🌐 Django 查找模板的两大机制:
Django 会通过以下 两种方式 来查找模板:
✅ 方式 1:全局模板目录(TEMPLATES → DIRS)
结构示例:
project_root/
├── templates/
│ └── home_application/
│ └── index_home.html
settings.py 配置:
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True, # 可有可无,和 app 模板无关
},
]
引用方式:
render(request, "home_application/index_home.html")
✅ 方式 2:每个 App 下的模板目录(依赖 APP_DIRS: True)
这个方式 才与 APP_DIRS: True 设置有关。
结构示例:
project_root/
├── home_application/
│ ├── templates/
│ │ └── home_application/
│ │ └── index_home.html
│ ├── views.py
settings.py 配置:
TEMPLATES = [
{
...
'APP_DIRS': True,
},
]
要求:
- 模板文件夹必须为:<app>/templates/<app>/
- 文件路径必须写完整(包括中间那层 <app>)
引用方式:
render(request, "home_application/index_home.html")
🔍 查找顺序(优先级)
Django 查找模板时,遵循以下顺序:
- 按顺序扫描 TEMPLATES['DIRS'] 列表 指定的全局目录。
- 如果找不到,才会去每个 app 中查找: 条件是 APP_DIRS=True 并且 app 必须在 INSTALLED_APPS 中注册
🧱 查找的核心依赖
| 要素 | 作用描述 |
|---|---|
TEMPLATES['DIRS'] | 指定自定义的全局模板路径 |
APP_DIRS: True | 启用从 app 的 templates/ 子目录查找模板 |
INSTALLED_APPS | 只有被注册的 app,其模板才会被查找 |
| 模板路径 | render() 传入的路径必须是相对于 template 根目录的路径 |
| 模板结构 | 对于 app 模板,必须为 <app>/templates/<app>/ |
⚠️ 常见错误总结(你当前问题就属于这一类)
| 错误 | 描述 |
|---|---|
❌ 模板放在了 <app>/templates/ 而不是 <app>/templates/<app>/ | |
❌ 忘记在 INSTALLED_APPS 中注册 app | |
❌ 拼写模板路径时少了中间那层 <app> | |
❌ APP_DIRS: True 没写,或者 TEMPLATES 配置格式不对 | |
| ❌ 文件名拼错(大小写、下划线、后缀等) | |
| ❌ 重启开发服务器后未刷新配置变更 |
✅ 推荐结构(兼容所有用法)
project_root/
├── templates/ # 可选(用于全局模板)
│ └── base.html
├── home_application/
│ ├── templates/
│ │ └── home_application/
│ │ └── index_home.html
│ ├── views.py
├── settings.py
✅ 推荐模板引用方式
根据模板放置位置不同,引用方式要匹配路径:
- templates/home_application/index_home.html → "home_application/index_home.html"
- home_application/templates/home_application/index_home.html → "home_application/index_home.html"
🧠 小结一句话:
Django 渲染模板时,查找路径 = TEMPLATES['DIRS'] 路径列表 + 所有已注册 App 中的 <app>/templates/<app>/,条件是 APP_DIRS=True。
评论(0)