2013-04-05 71 views
4

我一直在模仿一段时间的模板,而且我非常喜欢django体验的每一刻。然而,由于Django是这样一个大风扇松耦合,我想知道,为什么不把这段代码:的Django中的模板目录逻辑

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默认为第二个代码示例,而不是第一个?

回答

4

你问,“为什么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,) 

(使用名称os.pardiros.sep讲清楚我的意图)

+0

对不起,我的默认到第二。我真的不知道为什么,在这里运行django 1.5。 – 2013-04-05 11:07:34

+0

当你运行'django-admin.py startproject mysite'时,它会复制一个模板项目布局,并且在1.5中[settings.py的源代码在这里](https://github.com/django/django/blob/稳定/ 1.5.x的/ Django的/ conf目录/ project_template/PROJECT_NAME/settings.py)。也许你有一个本地补丁?或者你从其他地方获得项目模板? – 2013-04-05 11:16:44

+0

我相信是这样的,我的python安装与做事的方式有些不同。感谢防弹版本,它看起来很酷。 – 2013-04-05 11:19:52