django项目总监的路径

时间:2015-08-20 13:46:06

标签: python django

这是我的项目树:

projectname
    projectname
        init.py
        settings.py
        urls.py
        wsgi.py
    appname
        init.py
        admin.py
        models.py
        test.py
        views.py
        urls.py
    templates
        base.html
        login.html

现在在settings.py中我正在使用此代码:

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(BASE_DIR), "projectname", "templates"),
    )

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "projectname", "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "projectname", "static", "media")

如何获取项目目录的路径,以便我不需要在代码中键入项目名称projectname并在任何其他django项目中使用该代码?

更新

或者我可以使用这个

BASE_DIR+'/templates'
BASE_DIR+'/static/media'

或者这是一个坏主意?

2 个答案:

答案 0 :(得分:1)

我建议您使用os.path.abspath

# Project root is intended to be used when building paths,
# e.g. ``os.path.join(PROJECT_ROOT, 'relative/path')``.
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))

# Absolute path to the directory where ``collectstatic``
# will collect static files for deployment.
#
# For more information on ``STATIC_ROOT``, visit
# https://docs.djangoproject.com/en/1.8/ref/settings/#static-root
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')

# Absolute path to the directory that will hold uploaded files.
#
# For more information on ``MEDIA_ROOT``, visit
# https://docs.djangoproject.com/en/1.8/ref/settings/#media-root
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'uploads/')

答案 1 :(得分:0)

BASE_DIR 已经包括" projectname"。当你执行os.path.dirname(BASE_DIR)时,你从项目名一个级别;只是把它重新加入。不要这样做。

相反,只需直接使用BASE_DIR:

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, "templates"),
)