Python Django中的模板目录逻辑
我一直在玩弄模板已经有一段时间了,我喜欢django体验的每一刻。然而,由于django是一个松散耦合的大风扇,我想知道,为什么不使用这段代码:Python Django中的模板目录逻辑,python,django,Python,Django,我一直在玩弄模板已经有一段时间了,我喜欢django体验的每一刻。然而,由于django是一个松散耦合的大风扇,我想知道,为什么不使用这段代码: import os import platform if platform.system() == 'Windows': templateFiles = os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/') else: templateF
import os
import platform
if platform.system() == 'Windows':
templateFiles = os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/')
else:
templateFiles = os.path.join(os.path.dirname(__file__), '..', 'templates')
TEMPLATE_DIRS = (
# This includes the templates folder
templateFiles,
)
而不是:
import os
TEMPLATE_DIRS = (
templateFiles = os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/')
)
第一个示例是否比第二个更好地遵循松耦合原理(我相信是这样),如果是这样,为什么django默认为第二个代码示例而不是第一个?您会问,“为什么django默认为第二个代码示例?”但在django 1.5中,当我运行
$ django-admin.py startproject mysite
我发现settings.py
包含:
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
所以我不确定您的示例代码来自哪里:它不是Django的默认代码
在非Windows系统上,在目录名中很少发现反斜杠,因此您的第二个示例可能适用于所有实际情况。如果我要防弹,我会写:
import os
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
if os.sep != '/':
# Django says, "Always use forward slashes, even on Windows."
TEMPLATE_DIR = TEMPLATE_DIR.replace(os.sep, '/')
TEMPLATE_DIRS = (TEMPLATE_DIR,)
(使用名称并明确说明我的意图。)对不起,我的默认为第二个。我真的不知道为什么,在这里运行django 1.5。当您运行
django-admin.py startproject mysite
时,它会复制一个模板项目布局,在1.5中。也许你有本地补丁?或者您是从其他地方获得项目模板的?我相信是的,我安装的python与普通的方式有点不同。谢谢你的防弹版本,它看起来真的很酷。