項目目錄結構
├── 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