Skip to content

Instantly share code, notes, and snippets.

@alecordev
Created March 19, 2017 17:48
Show Gist options
  • Save alecordev/6daf2e12d51476c5baa850db322869a4 to your computer and use it in GitHub Desktop.
Save alecordev/6daf2e12d51476c5baa850db322869a4 to your computer and use it in GitHub Desktop.
Some Django customizations
Fixing Settings
We’re on a mission to fix your bad settings files here. We show this layout to new clients and I’m constantly surprised how few people know this is even possible to do. I blame the fact that while everyone knows that settings are just Python code, they don’t think about them as Python code.
So let’s fix up our settings. For our foo project we’re going to have 4 environments: dev, stage, jenkins, and production. So let’s give each it’s own file. The process to do this is:
In foo/foo/ make a settings directory and create an empty __init__.py file inside it.
Move foo/foo/settings.py into foo/foo/settings/base.py
Create the individual dev.py, stage.py, jenkins.py, and prod.py files in foo/foo/settings/. Each of these 4 environment specific files should simply contain the following:
from base import *
So why is this important? Well for local development you want DEBUG=True, but it’s pretty easy to accidentally push out production code with it on, so just open up foo/foo/settings/prod.py and after the initial import from base just add DEBUG=False. Now if your production site is safe from that silly mistake.
What else can you customize? Well it should be pretty obvious you’ll likely have staging, jenkins, and production all pointing at different databases, likely even on different hosts. So adjust those settings in each environment file.
Using these settings
Using these settings is easy, no matter which method you typically use. To use the OS’s environment you just do:
export DJANGO_SETTINGS_MODULE=“foo.settings.jenkins”
And boom, you’re now using the jenkins configuration.
Or maybe you prefer to pass them in as a commandline option like this:
./manage.py migrate —settings=foo.settings.production
Same if you’re using gunicorn:
gunicorn -w 4 -b 127.0.0.1:8001 —settings=foo.settings.dev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment