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


当前回答

要向上移动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

其他回答

要向上移动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

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

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

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

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

从工作目录上升一级

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

或从当前目录

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

你想要的就是:

BASE_DIR = os.path.join( os.path.dirname( __file__ ), '..' )

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