2013-04-05 72 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