项目目录结构
├── app1
│ │ urls.py
│ │ views.py
│ └── ...
│
├── app2
│ │ urls.py
│ │ views.py
│ └── ...
│
├── django_test
│ │ settings.py
│ │ urls.py
│ └── ...
│
└── templates
└── home.html
django_test\settings.py
INSTALLED_APPS = [
...
# 添加APP
'app1',
'app2',
]
...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 修改 DIRS
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
...
},
]
return render(request, 'home.html')
优先加载 templates\home.html, 如果不存在, 再去加载各个app目录下的 templates\home.html.
假设 app1 与 app2 都存在 templates\home.html, 则按照设置 INSTALLED_APPS 里APP的顺序, 无论是 app1 或 app2 调用 home.html, 都只会加载 app1 的 templates\home.html.
解决办法
项目目录结构
├── app1
│ │ urls.py
│ │ views.py
│ │ ...
│ └── templates
│ └── app1
│ └── home.html
│
├── app2
│ │ urls.py
│ │ views.py
│ │ ...
│ └── templates
│ └── app2
│ └── home.html
│
│── django_test
│ │ settings.py
│ │ urls.py
│ └── ...
│
└── templates
└── home.html
return render(request, 'home.html') 加载 templates\home.html
return render(request, 'app1/home.html') 加载 app1\templates\app1\home.html
return render(request, 'app2/home.html') 加载 app2\templates\app2\home.html

本文详细解析了Django框架中模板加载的顺序和机制,包括如何优先加载特定目录下的模板文件,以及如何通过修改settings配置来调整模板加载路径。同时介绍了当多个应用存在相同模板时,如何确保正确加载目标模板的方法。
1万+

被折叠的 条评论
为什么被折叠?



