我最近把Django从v1.3.1升级到了v1.4。

在我的旧设置。py我有

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname( __file__ ), 'templates').replace('\\', '/'),
    # 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.
)

这将指向/Users/hobbes3/Sites/mysite/templates,但因为Django v1.4将项目文件夹移动到与应用文件夹相同的级别,我的settings.py文件现在在/Users/hobbes3/Sites/mysite/而不是/Users/hobbes3/Sites/mysite/。

所以实际上我的问题是双重的

如何使用操作系统。查看__file__上一级目录的路径。换句话说,我想要/Users/hobbes3/Sites/mysite/ settings.py使用相对路径找到/Users/hobbes3/Sites/mysite/templates。 我应该保持模板文件夹(其中有跨应用模板,如管理,注册等)在项目/User/hobbes3/Sites/mysite级别或在/User/hobbes3/Sites/mysite/mysite?


当前回答

我认为最简单的方法就是重用dirname() 所以你可以调用

os.path.dirname(os.path.dirname( __file__ ))

如果你的文件在/Users/hobbes3/Sites/mysite/templates/method.py

返回"/Users/hobbes3/Sites/mysite"

其他回答

对我这样的偏执狂来说,我更喜欢这个

TEMPLATE_DIRS = (
    __file__.rsplit('/', 2)[0] + '/templates',
)

如果你使用的是Python 3.4或更新版本,一个方便的方法是pathlib:

from pathlib import Path

full_path = "path/to/directory"
str(Path(full_path).parents[0])  # "path/to"
str(Path(full_path).parents[1])  # "path"
str(Path(full_path).parents[2])  # "."

就我个人而言,我倾向于函数方法

def get_parent_dir(directory):
    import os
    return os.path.dirname(directory)

current_dirs_parent = get_parent_dir(os.getcwd())

从当前文件路径你可以使用:

os.path.join(os.path.dirname(__file__),'..','img','banner.png')
from os.path import dirname, realpath, join
join(dirname(realpath(dirname(__file__))), 'templates')

更新:

如果你碰巧通过符号链接“复制”settings.py, @forivall的答案更好:

~user/
    project1/  
        mysite/
            settings.py
        templates/
            wrong.html

    project2/
        mysite/
            settings.py -> ~user/project1/settings.py
        templates/
            right.html

上面的方法将“看到”wrong.html,而@forivall的方法将看到right.html

在没有符号联系的情况下,这两个答案是相同的。