我最近把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?


当前回答

使用os。我们可以向上走一个目录

one_directory_up_path = os.path.dirname('.')

同样,在找到您想要的目录后,您可以与其他文件/目录路径连接

other_image_path = os.path.join(one_directory_up_path, 'other.jpg')

其他回答

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

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

current_dirs_parent = get_parent_dir(os.getcwd())

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

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

从工作目录上升一级

import os
os.path.dirname(os.getcwd())

或从当前目录

import os
os.path.dirname('current path')

当然:只需使用os.chdir(..)。

要向上移动n个文件夹…运行了(n)

import os

def up(n, nth_dir=os.getcwd()):
    while n != 0:
        nth_dir = os.path.dirname(nth_dir)
        n -= 1
    return nth_dir