[Django]-Django, use conditional settings module in wsgi.py

4👍

Well how about this approach, create three settings files:

  • settings.py (master)
  • settings_dev.py (override some settings for development server)
  • settings_prod.py (override some settings for production server)

At the end of settings.py file check if DEBUG=True then import settings_dev.py else settings_prod.py:

settings.py:

----
try:
    if DEBUG:
        from settings_dev import *
    else:
        from settings_prod import *
except ImportError:
    pass

Using this approach you will only need to set:

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

Now don’t say that what if I forgot to change the DEBUG value for specific servers. Then the other solution is that have two separate repositories add settings_prod.py in git ignore list for development repository and add settings_dev.py in git ignore list for production. Always set DEBUG=False in settings_prod.py and DEBUG=True in settings.py file, then at the end of settings.py file do this instead:

try:
    from settings_dev import *
except ImportError:
    try:
        from settings_prod import *
    except ImportError:
        pass

0👍

You could also use an environment variable (or the machine- or user-name) to distinguish different machines. Preferably you set it on the debug-one and never on production, so it can not be forgotten. Something along

if "yes" == os.environ.get("DJANGO_DEBUG_ENABLED"): 
    DEBUG = True
    # or 
    from settings_dev import *
else:
    DEBUG = False
    # or 
    from settings_prod import *

Alternatively you could put a file there which is not part of the repository and check for its presence / absence, or import the DEBUG from a settings_local.py.

Leave a comment