django 模版加載順序與模版存放結構位置

項目目錄結構

├── 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.

假設 app1app2 都存在 templates\home.html, 則按照設置 INSTALLED_APPS 裏APP的順序, 無論是 app1app2 調用 home.html, 都只會加載 app1templates\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






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章