Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

At the top of settings.py 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).

like image 970
boatcoder Avatar asked Dec 02 '25 04:12

boatcoder


1 Answers

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.

like image 154
Chris W. Avatar answered Dec 03 '25 19:12

Chris W.