告诉django来搜索应用的模板子文件夹 [英] Tell django to search app's template subfolders
问题描述
我的django应用程序中的模板有以下文件夹结构:
templates /
app /
model1 /
model1_form.html
model2 /
model2_form.html
假设我正在使用model1和一个通用的ListView,现在它只在templates / app / model1_form.html中进行搜索。有没有办法我可以告诉django他还应该搜索应用程序/子文件夹?我不想手动设置模板名称和路径( template_name =templates / app / model1 / model1_form.html
)。
在settings.py我有:
import os.path
/ pre>
BASE_PATH = os.path.dirname(os.path.dirname(__ file__))
TEMPLATE_DIRS =(
BASE_PATH +'/ templates /',
)
这是我的观点:
class HousesListView ):
model = House
context_object_name =house_list
提前感谢
解决方案您需要添加
django.template.loaders.app_directories.Loader
到TEMPLATE_LOADERS
(如果还没有)。TEMPLATE_LOADERS = (
/ pre>
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
然后,更改你的文件夹st结构,使您在应用程序目录中有一个templates文件夹:
- < project_root>
- app
- 模板
- model1
- model2
- < project_root>
或者正确命名空间模型,以便不会与其他应用程序名称意外冲突:
- app
- 模板
- app
- model1
- model2
I have the following folder structure for the templates on my django app:
templates/ app/ model1/ model1_form.html model2/ model2_form.html
Suppose I'm using model1 and a generic ListView, right now it only searches at templates/app/model1_form.html. Is there anyway I can tell django he should also search the app/ subfolders? I don't want to have to set the template name and path manually (
template_name="templates/app/model1/model1_form.html"
).At settings.py I have:
import os.path BASE_PATH = os.path.dirname(os.path.dirname(__file__)) TEMPLATE_DIRS = ( BASE_PATH+'/templates/', )
This is my view:
class HousesListView(ListView): model = House context_object_name = "house_list"
Thanks in advance!
解决方案You need to add
django.template.loaders.app_directories.Loader
toTEMPLATE_LOADERS
(if it's not already).TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )
Then, change your folder structure such that you have a "templates" folder in the app directory:
- <project_root> - app - templates - model1 - model2
Or to properly namespace the models so they don't clash with other app names accidentally:
- <project_root> - app - templates - app - model1 - model2
这篇关于告诉django来搜索应用的模板子文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!