Dotenv

1. Installing dotenv

To keep your your secret_key and other sensitive stuff (like database connection) out of your git repo, you can use a .env file to put them in.

When you've activated your virtual environment, install python-dotenv. This tool will help Django to read settings from your .env file.

pip install python-dotenv

2. Create a .env file

In your Django project's main folder, create a .env file. A very simple version could look like this:

ALLOWED_HOSTS = localhost myhost someotherhost
SECRET_KEY = <a_very_long_and_very_secret_key>
DEBUG = True
  • SECRET_KEY is used for all kinds of things, like cryptographic signing, sessions, password reset tokens etc. So that's why you don't want this in your git repo, and to keep ik secure.
  • DEBUG is used to get more information out of your error messages. You want this to be False on your production environment, and True on your development environment.

3. Setting up Django

To have Django be able to use your .env file, edit your settings.py file and add a couple of lines at the top. It should look a bit like this:

import os
from dotenv import load_dotenv

# Load environment variables from a .env file
load_dotenv()

And replace the ALLOWEDHOSTS, SECRETKEY and DEBUG lines with this:

ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS').split(' ') # I'll have to check if this works, not tried it yet
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = os.getenv('DEBUG')
  • [ ] Test if ALLOWED_HOSTS works with this dotenv setup #T-15-m #test #django

4. Tips

  • Keep your .env out of your git repository. Use a good [[Git#336a9a|.gitignore]] file for this.
  • You can also use this in other parts of your project. For example, if you have an API_KEY set in your .env, you can use it in your views:
# views.py
import os

def some_view(request):
    api_key = os.getenv('API_KEY')
    ...