Per-host settings.py for Django projects

When working as part of a team on a Django project, it is often useful to have a per-host settings file. There are many ways to do this but the approach that I liked most is creating a local_settings.py file in each environment.

I’m often the only programmer on web projects, but even then I still find it helpful to have a local_settings.py file on my local host. In it I include things such as debug-related settings, test keys for the different API providers, a modified logger configuration and flags that turn off any added security measures.

As part of a team, this gives me the added benefit that each team member gets to use any local tools or configuration that they prefer while maintaining control over the production environment. Anything in local_settings.py that can apply globally gets promoted to settings.py. I find this decreases any chances of politics or religious wars over tooling that programmers are famous for.

This is a typical snippet that I include in every settings.py file.

This allows me to override settings on a per-host basis and has minimal impact on performance. It also allows me to add any debug utilities, apps or middleware, to a running instance.

My local_settings.py file would look something like this.

As you can see, this snippet does a number of useful things. It turns on the debug flags. It sets the email backend to print emails to console instead of actually sending them out. It defines and configures a set of locally installed apps that help with development but shouldn’t be on the production server. It also sets the default database to use sqlite instead of whatever one is used in production(Postgres).

This technique will also offer some protection against mistakes such as forgetting to turn off your DEBUG flag before deploying to your production server. And will save you from feeling silly when you mass email your userbase with a test email. I, of course, have never done anything like that before. Ahem, you can thank me later…

Leave a Reply

Your email address will not be published. Required fields are marked *