Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django settings.py: Separate local and global configuration

I was wondering if it was possible to separate the "local" configuration in Django (Local path to static, templates content which have to be absolute, local DB info, etc...) from the "global" configuration (URL, Middleware classes, installed apps, etc...) so that several people can work on a same project over Git or SVN without having to rewrite the local settings every time there is a commit done!

Thanks!

like image 625
nbarraille Avatar asked Apr 07 '11 14:04

nbarraille


People also ask

Where are Django settings stored?

A Django settings file doesn't have to define any settings if it doesn't need to. Each setting has a sensible default value. These defaults live in the module django/conf/global_settings.py .

What does settings py do in Django?

settings.py is a core file in Django projects. It holds all the configuration values that your web app needs to work; database settings, logging configuration, where to find static files, API keys if you work with external APIs, and a bunch of other stuff.


1 Answers

Yes, definitely. The settings.py file is just Python, so you can do anything in there - including setting things dynamically, and importing other files to override.

So there's two approaches here. The first is not to hard-code any paths, but calculate them dynamically.

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = [
    os.path.join(PROJECT_ROOT, "templates"),
]

etc. The magic Python keyword __file__ gives the path to the current file.

The second is to have a local_settings.py file outside of SVN, which is imported at the end of the main settings.py and overrides any settings there:

try:
    from local_settings import *
except ImportError:
    pass

The try/except is to ensure that it still works even if local_settings is not present.

Naturally, you could try a combination of those approaches.

like image 185
Daniel Roseman Avatar answered Sep 27 '22 02:09

Daniel Roseman