开发者

How do I modify DATABASES variable when including local_settings.py from a django settings.py

At the top of settings.开发者_如何学Gopy I have:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dbname',
        'USER': 'dbuser',
        'PASSWORD': 'pw'
        'HOST': '',
        'PORT': '',
    }
}

At the bottom I have:

try:
    from local_settings import *
except ImportError:
    pass

In the local_settings.py, I'd like to modify DATABASES['default']['host'] that is defined in the settings.py file.

Is this possible? If so, how? I don't want to duplicate the whole DATABASES setting, I just want to adjust the HOST (to point at another server).


Use this in your settings.py.

try:
    from local_settings import *
    for k,v in _DATABASES:
        if k in DATABASES:
            DATABASES[k].update(v)
        else:
            DATABASES[k] = v
except ImportError:
    pass

With something like this in your local_settings.py.

_DATABASES = {"default":{"HOST":"new_host"}}

EDIT: Note I've changed my code per @saverio's comment about nested dictionaries.


Try this in local_settings.py:

import settings

settings.DATABASES['default']['HOST'] = 'my_host'

Hope this helps!


typically I reverse it, so settings.py overrides local_settings.py from local_settings import * at the top of settings.py. Normally db settings are on location based setting, i.e. dev db for dev work and really do not add db settings to settings.py. In my mind settings.py should define settings that are required in every location that the project is running and shouldn't be over written by a subset.


You can use execfile() instead of an import. That gives you access to everything in settings.py's scope:

execfile(os.path.join(os.path.dirname(__file__), 'local_settings.py'))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜