Search code examples
djangodjango-settings

How do I import settings when using DJANGO_SETTINGS_MODULE?


I have a Django project and am using the DJANGO_SETTINGS_MODULE for managing each environment settings. I have created different settings files for each environment, however, I'm confused how I can access these settings without having to change the imports in my code. For example, I have this settings directory structure:

stats/
    config/
        settings/
            __init__
            base.py
            dev.py
            prod.py

base.py has all my default settings, include some API keys for third party services. I override these in each environment:

base.py

API_KEY  = "default"

dev.py

from base import *
API_KEY = "dev"

prod.py

from base import *
API_KEY = "prod"

When I start up my server, I use

./manage.py runserver --settings=stats.config.settings.dev

But how do I access the API_KEY without having to change "dev" to "prod" every time I deploy? This is how I currently access the API_KEY in my code:

from stats.config.settings.dev import API_KEY

I can't seem to find the proper answer to this anywhere. Thanks!


Solution

  • You access your settings via django.conf.settings, you're not supposed to import/access them directly

    from django.conf import settings
    settings. API_KEY