David542
David542

Reputation: 110342

How to do if imports if multiple settings files

I have three settings files in a django project, so for example in my wsgi file I can do:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings_staging')

But then my question is, how would I do imports everywhere else in the project? For example:

from settings import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY

This wouldn't be from "settings" anymore, but from "settings_staging".

Upvotes: 0

Views: 94

Answers (2)

David542
David542

Reputation: 110342

Another possible approach and the one I ended up doing is to have one settings file and then a STAGE where you can import more sensitive credentials. It looks like this:

# settings.py

# Part1 -- all my initial settings

# Part2 -- load in any sensitive variables
if STAGE == 'LOCAL':
    pass
elif STAGE == 'STAGING':
    from settings_staging import *
elif STAGE == 'PRODUCTION':
    from settings_production import *

# Part3 -- finish up loading settings, such as DB, CACHE, etc.

And in the wsgi file you can do something like:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
os.environ.setdefault('STAGE', 'staging')

This way by just changing the STAGE environment -- whether it's wsgi, local, or anywhere else, you can have all the settings correct.

Upvotes: 1

solarissmoke
solarissmoke

Reputation: 31464

You don't import the settings directly from your settings file, but load them via django.conf.settings. From the documentation:

In your Django apps, use settings by importing the object django.conf.settings. Example:

from django.conf import settings

if settings.DEBUG:
       # Do something

django.conf.settings will itself correctly load the settings file you want to use based on the settings module you specify in wsgi.py.

manage.py also looks for an environment variable specifying which settings module to use, so you can choose which settings module to use by setting the enviroment variable, e.g., :

export DJANGO_SETTINGS_MODULE=settings_development
./manage.py runserver

Upvotes: 3

Related Questions