在django项目中放置模板的最佳位置是什么?
在django项目中放置模板的最佳位置是什么?
放置在<PROJECT>/<APP>/templates/<APP>/template.html
中,用于特定于应用程序的模板,以帮助使应用程序在其他地方可重用。
对于一般的"全局"模板,我把它们放在<PROJECT>/templates/template.html
所有回答
从Dominic和dlrust跟进,
我们使用setuptools源代码分发(sdist)来打包我们的django项目和应用程序,以便在我们不同的环境中部署。
我们发现模板和静态文件需要在django应用程序目录下,以便它们可以被setuptools打包。
例如,我们的模板和静态路径看起来像:
PROJECT/APP/templates/APP/template.html
PROJECT/APP/static/APP/my.js
要做到这一点,MANIFEST.in 需要修改(见http://docs.python.org/distutils/sourcedist.html#the-manifest-in-template)
的一个例子MANIFEST.in:
include setup.py
recursive-include PROJECT *.txt *.html *.js
recursive-include PROJECT *.css *.js *.png *.gif *.bmp *.ico *.jpg *.jpeg
此外,您需要在django设置文件中确认app_directories加载器在您的TEMPLATE_LOADERS中。 我认为它在django1.4中默认存在。
Django设置模板加载器的一个例子:
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
以防万一,您想知道为什么我们使用sdist而不仅仅是处理rsync文件;这是我们配置管理工作流程的一部分,我们有一个单一的构建tarball,它在测试,验收和生产环
DJANGO1.11
添加模板文件夹manage.py 存在,这是你的基目录。 更改模板的DIRS,如下所示settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
现在通过使用代码来使用模板 ,
def home(request):
return render(request,"index.html",{})
在views.py... 这对于django1.11来说工作完全正常
我明白TEMPLATE_DIRS
需要一个绝对路径。 而且我不喜欢我的代码中的绝对路径。
所以这对我来说效果很好,在settings.py
:
import os
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(os.path.realpath(__file__)),
"../APPNAME/templates")
)
Django1.10
TEMPLATE_DIRS
已弃用。
现在我们需要在Django1.8中使用TEMPLATE
,这样:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
# ... some options here ...
},
},
]
定义模板后,您可以安全地删除ALLOWED_INCLUDE_ROOTS、TEMPLATE_CONTEXT_PROCESSORS、TEMPLATE_DEBUG、TEMPLATE_DIRS、TEMPLATE_LOADERS和TEMPLATE_STRING_IF_INVALID。
关于最佳位置,Django寻找这样的模板 :
- DIRS定义了引擎应按搜索顺序查找模板源文件的目录列表。
- APP_DIRS告诉引擎是否应该在已安装的应用程序中查找模板。 每个后端都为应存储其模板的应用程序内的子目录定义一个常规名称。
更多资料 : https://docs.djangoproject.com/en/1.10/topics/templates/#configuration
以前的解决方案在我的情况下不起作用。 我用过:
TEMPLATE_DIRS = [ os.path.join(os.path.dirname(os.path.realpath(__file__)),"../myapp/templates") ]
您也可以考虑使用django-dbtemplates将模板放在数据库中。 它也是缓存和django-reversion应用程序的设置,它可以帮助您保留旧版本的模板。
它工作得很好,但我更喜欢在导入/同步到/从文件系统方面有更多的灵活性。
[编辑:20Aug2018-此存储库不可用,具有相同名称的存储库可在https://github.com/jazzband/django-dbtemplates并于8个月前更新。 我不再以任何有意义的方式使用Django,所以不能保证这一点。]
来自Django书,第4章:
这正是我所做的,对我很有效。
我的目录结构看起来像这样:
/media
对于我所有的CSS/JS/图像等/templates
对于我的模板/projectname
主要项目代码(即Python代码)