Django - 在协作项目中如何处理settings.py中的路径
我刚开始为我的公司研究Django的可行性,发现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.
)
我想问的是:在团队合作时,如何处理这些绝对路径呢?比如说,如果一个团队成员在从源代码管理系统获取项目后需要修改这些路径,这不仅容易出错,还会浪费时间。而且,当这个用户需要提交对settings.py所做的更改时,也会引发一些麻烦。我该如何避免这种情况呢?
5 个回答
3
这样做:
import os
ROOT_PATH = os.path.dirname(__file__)
.
.
.
TEMPLATE_DIRS = (
os.path.join(ROOT_PATH, 'templates'),
)
这样可以根据settings.py文件所在的目录来设置路径。
3
settings.py
其实就是一个普通的 Python 模块。你可以导入并使用 os.path
里面的各种函数来构建你的路径。
31
import os.path
#Get the absolute path of the settings.py file's directory
PWD = os.path.dirname(os.path.realpath(__file__ ))
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.
#Add Templates to the absolute directory
os.path.join(PWD, "Templates")
)
这是我进行相对导入的方法。请注意,通常建议你有一个单独的localsettings.py文件,或者类似的文件。