简体   繁体   中英

Django - How to deal with the paths in settings.py on collaborative projects

I have just started a feasibility study on Django for my company and I have noticed the need for absolute paths on 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.
)

My question is: How to deal with these absolute path when you're collaborating with a team? Say, if a team member has to modify the paths after getting the project from source control not only will this be error prone and time wasteful but it will also cause complications when this user has to commit a change made to settings.py. How can I avoid this?

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") 
)

That's how I do relative imports. Note that is usually wise to have a separate localsettings.py file, or something similar.

Do this:

import os
ROOT_PATH = os.path.dirname(__file__)
.
.
.
TEMPLATE_DIRS = (
    os.path.join(ROOT_PATH, 'templates'),
)

This will set the paths according to the directory of settings.py file

settings.py is just another Python module. Import and use the various functions in os.path to build your paths.

The alternative to using relative path from the settings.py file, is for each developer to have their own settings.py.

# settings.py
TEMPLATE_DIRS = (
    'c:\django\templates\',
)

# dev-x-settings.py
import settings
TEMPLATE_DIRS = (
    'd:\dev\django\project\templates\'
)

The dev-x-settings.py imports all the settings from the base file, and changes the bits and pieces they need to. Also very handy for maintaining a local sqlite database and the like.

We usually set out our settings as:

/settings/
    __init__.py
    production.py
    staging.py
    test.py
    dev-x.py
    dev-y.py

Then all you need to worry about is running the server and passing it the correct settings.py file.

Besides using os.path you could add

try:
    import * from settings_local
except:
    pass

at the end of you settings.py . Every developer can then create his own settings_local.py file which is not checked in into the VCS!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM