How to Configure Django Settings: Best Practices
Tags: django, djangosettings
Published: 2019-07-09 00:46:46

---
title: How to Configure Django Settings: Best Practices
cover_image: https://cdn-images-1.medium.com/max/800/1*s7q6fK9HVDoRCjJdIjMvWg.png
published: true
description: 
tags: django, django settings
canonical_url: https://djangostars.com/blog/configuring-django-settings-best-practices/
---

This article is intended for engineers who use the Django framework. It gives a deep insight into configuring Django project settings, and the pros and cons of different approaches. In the article you will also find recommendations concerning tools, best practices and architectural solutions, all time-tested and proven by successful projects.


## Managing Django Settings: Issues
**Different environments.** Usually, you have several environments: local, dev, ci, qa, staging, production, etc. Each environment can have its own specific settings (for example: <code>DEBUG = True</code>, more verbose logging, additional apps, some mocked data, etc). You need an approach that allows you to keep all these Django setting configurations.

**Sensitive data.** You have <code>SECRET_KEY</code> in each Django project. On top of this there can be DB passwords and tokens for third-party APIs like Amazon or Twitter. This data cannot be stored in VCS.

**Sharing settings between team members.** You need a general approach to eliminate human error when working with the settings. For example, a developer may add a third-party app or some API integration and fail to add specific settings. On large (or even mid-size) projects, this can cause real issues.

**Django settings are a Python code.** This is a curse and a blessing at the same time. It gives you a lot of flexibility, but can also be a problem – instead of key-value pairs, settings.py can have a very tricky logic.
## Setting Configuration: Different Approaches
There is no built-in universal way to configure Django settings without hardcoding them. But books, open-source and work projects provide a lot of recommendations and approaches on how to do it best. Let's take a brief look at the most popular ones to examine their weaknesses and strengths.
### settings_local.py
This is the oldest method. I used it when I was configuring a Django project on a production server for the first time. I saw a lot of people use it back in the day, and I still see it now.

The basic idea of this method is to extend all environment-specific settings in the <code>settings_local.py</code> file, which is ignored by VCS. Here’s an example:

<code>settings.py</code> file:

{% gist https://gist.github.com/alexryabtsev/b3660bf6112215f9bb93e0f8c0ce0826.js %}


<code>settings_local.py</code> file:

{% gist https://gist.github.com/alexryabtsev/39455aac4b238bb4f8e9c097c94105e5.js %}

<h3>Pros:</h3>
<ul>
 	<li>Secrets not in VCS.</li>
</ul>
<h3>Cons:</h3>
<ul>
 	<li><code>settings_local.py</code> is not in VCS, so you can lose some of your Django environment settings.</li>
 	<li>The Django settings file is a Python code, so <code>settings_local.py</code> can have some non-obvious logic.</li>
 	<li>You need to have <code>settings_local.example</code> (in VCS) to share the default configurations for developers.</li>
</ul>
<h3><a name="4"></a>Separate settings file for each environment</h3>
This is an extension of the previous approach. It allows you to keep all configurations in VCS and to share default settings between <a href="https://djangostars.com/services/python-django-development/">developers</a>.

In this case, you make a <code>settings</code> package with the following file structure:
<pre><code>settings/
   ├── __init__.py
   ├── base.py
   ├── ci.py
   ├── local.py
   ├── staging.py
   ├── production.py
   └── qa.py</code></pre>
settings/local.py:

{% gist https://gist.github.com/alexryabtsev/f275409df9842b6e9598f39a6ea621c1.js %}

To run a project with a specific configuration, you need to set an additional parameter:

{% gist https://gist.github.com/alexryabtsev/51a4fe47c3ebbaea81ead91448edc765.js %}
<h3>Pros:</h3>
<ul>
 	<li>All environments are in VCS.</li>
 	<li>It's easy to share settings between developers.</li>
</ul>
<h3>Cons:</h3>
<ul>
 	<li>You need to find a way to handle secret passwords and tokens.</li>
 	<li>"Inheritance" of settings can be hard to trace and maintain.</li>
</ul>
<h3><a name="5"></a>Environment variables</h3>
To solve the issue with sensitive data, you can use environment variables.
{% gist https://gist.github.com/alexryabtsev/00ba08707672541ac8be227d869241a2.js %}

This is the simplest example using Python <code>os.environ</code> and it has several issues:
<ol>
 	<li>You need to handle <code>KeyError</code> exceptions.</li>
 	<li>You need to convert types manually (see <code>DATABASE_PORT</code> usage).</li>
</ol>
To fix <code>KeyError</code>, you can write your own custom wrapper. For example:
{% gist https://gist.github.com/alexryabtsev/5f8ff261bcf8e0e2274cbb0b827eeedb.js %}


Also, you can set default values for this wrapper and add type conversion. But actually there is no need to write this wrapper, because you can use a third-party library (we'll talk about this <a href="https://djangostars.com/blog/configuring-django-settings-best-practices/#7">later</a>).
<h3>Pros:</h3>
<ul>
 	<li>Configuration is separated from code.</li>
 	<li>Environment parity – you have the same code for all environments.</li>
 	<li>No inheritance in settings, and cleaner and more consistent code.</li>
 	<li>There is a theoretical grounding for using environment variables – <a href="https://djangostars.com/blog/configuring-django-settings-best-practices/#6">12 Factors</a>.</li>
</ul>
<h3>Cons:</h3>
<ul>
 	<li>You need to handle sharing default config between developers.</li>
</ul>
<h2><a name="6"></a>12 Factors</h2>
12 Factors is a collection of recommendations on how to build distributed web-apps that will be easy to deploy and scale in the Cloud. It was created by <a href="https://www.heroku.com/" rel="nofollow">Heroku</a>, a well-known Cloud hosting provider.

As the name suggests, the collection consists of twelve parts:
<ol>
 	<li>Codebase</li>
 	<li>Dependencies</li>
 	<li>Config</li>
 	<li>Backing services</li>
 	<li>Build, release, run</li>
 	<li>Processes</li>
 	<li>Port binding</li>
 	<li>Concurrency</li>
 	<li>Disposability</li>
 	<li>Dev/prod parity</li>
 	<li>Logs</li>
 	<li>Admin processes</li>
</ol>
Each point describes a recommended way to implement a specific aspect of the project. Some of these points are covered by instruments like Django, Python, pip. Some are covered by design patterns or the infrastructure setup. In the context of this article, we are interested in one part: the <a href="https://12factor.net/config" rel="nofollow">Configuration</a>.

Its main rule is <strong>to store configuration in the environment</strong>. Following this recommendation will give us strict separation of config from code.

You can read more on <a href="https://12factor.net/" rel="nofollow">12factor.net</a>.
<h2><a name="7"></a>django-environ</h2>
Based on the above, we see that <strong>environment variables are the perfect place to store settings</strong>.

Now it's time to talk about the toolkit.

Writing code using <code>os.environ</code> could be tricky sometimes and require additional effort to handle errors. It's better to use <a href="https://django-environ.readthedocs.io/en/latest/" rel="nofollow"><strong>django-environ</strong></a> instead.

Technically it's a merge of:
<ul>
 	<li><a href="https://github.com/rconradharris/envparse">envparse</a></li>
 	<li><a href="https://github.com/nickstenning/honcho">honcho</a></li>
 	<li><a href="https://github.com/kennethreitz/dj-database-url">dj-database-url</a></li>
 	<li><a href="https://github.com/dstufft/dj-search-url">dj-search-url</a></li>
 	<li><a href="https://github.com/julianwachholz/dj-config-url">dj-config-url</a></li>
 	<li><a href="https://github.com/ghickman/django-cache-url">django-cache-url</a></li>
</ul>
This app gives a well-functioning API for reading values from environment variables or text files, handful type conversion, etc. Let's look at some examples.

<code>settings.py</code> file before:

{% gist https://gist.github.com/alexryabtsev/897a963ec458b2f2bdfc7d79e6b9b43f.js %}


<code>settings.py</code> file after:

{% gist https://gist.github.com/alexryabtsev/8acdbe71c83aca23206f81c1cbb7dd03.js %}


<code>.env</code> file:

{% gist https://gist.github.com/alexryabtsev/1ab194568218ee79cf5626f75205b844.js %}

<h2><a name="8"></a>Setting Structure</h2>
Instead of splitting settings by environments, you can split them by the source: Django, third- party apps (Celery, DRF, etc.), and your custom settings.

File structure:
<pre><code>project/
├── apps/
├── settings/
│   ├── __init__.py
│   ├── djano.py
│   ├── project.py
│   └── third_party.py
└── manage.py
</code></pre>
<code>__init__.py</code> file:

{% gist https://gist.github.com/alexryabtsev/9b6196bb642415871cf8d7de0ebc72cd.js %}


Each module could be done as a package, and you can split it more granularly:
<pre><code>project/
├── apps/
├── settings/
│   ├── project
│   │   ├── __init__.py
│   │   ├── custom_module_foo.py
│   │   ├── custom_module_bar.py
│   │   └── custom_module_xyz.py
│   ├── third_party
│   │   ├── __init__.py
│   │   ├── celery.py
│   │   ├── email.py
│   │   └── rest_framework.py
│   ├── __init__.py
│   └── djano.py
└── manage.py
</code></pre>
<h2><a name="9"></a>Naming Conventions</h2>
Naming of variables is one of the most complex parts of development. So is naming of settings. We can’t imply on Django or third-party applications, but we can follow these simple rules for our custom (project) settings:
<ul>
 	<li>Give meaningful names to your settings.</li>
 	<li>Always use the prefix with the project name for your custom (project) settings.</li>
 	<li>Write descriptions for your settings in comments.</li>
</ul>
<strong>Bad example:</strong>

{% gist https://gist.github.com/alexryabtsev/d329d9de4079561bbcdb5e573c640262.js %}

<strong>Good example:</strong>

{% gist https://gist.github.com/alexryabtsev/efd9f7337201664e6da6f38666f8e7ef.js %}


Change <code>MYAWESOMEPROJECT</code> to you real project name.
<h2><a name="10"></a>Django Settings: Best practices</h2>
<ul>
 	<li>Keep settings in environment variables.</li>
 	<li>Write default values for production configuration (excluding secret keys and tokens).</li>
 	<li>Don't hardcode sensitive settings, and don't put them in VCS.</li>
 	<li>Split settings into groups: Django, third-party, project.</li>
 	<li>Follow naming conventions for custom (project) settings.</li>
</ul>
<h2><a name="11"></a>Conclusion</h2>
The Settings file is a small but very important part of any Django project. If you do it wrong, you'll have a lot of issues during all phases of development. But if you do it right, it will be a good basis for your project that will allow it to grow and scale in the future.

Using the environment variables approach, you can easily switch from a monolith to microservice architecture, wrap your project in Docker containers, and deploy it in any VPS or Cloud hosting platform such as: Amazon, Google Cloud, or your own Kubernetes cluster.
<h2><a name="12"></a>Sources:</h2>
<ul>
 	<li><a href="https://12factor.net/" rel="nofollow">https://12factor.net/</a></li>
 	<li><a href="https://django-environ.readthedocs.io/en/latest/" rel="nofollow">https://django-environ.readthedocs.io/en/latest/</a></li>
 	<li><a href="https://www.twoscoopspress.com/collections/everything/products/two-scoops-of-django-1-11" rel="nofollow">Two Scopes of Django</a></li>


This article about [configuring Django settings](https://djangostars.com/blog/configuring-django-settings-best-practices/) is written by Alex Ryabtsev - Senior Software Engineer. originally posted on Django Stars blog.