Using source control tools, such as Git or Mercurial, is a good idea for projects of any size; however, some developers using these tools may overlook the importance of hiding sensitive information from their repository. This is especially important if the repository is public.
I recently had to take this into consideration when starting this website so I spent some time exploring my options. There are a few Django settings that I knew should be hidden: the project's secret key and the database connection information.
Two solutions are to use a settings file that is not tracked in source control or to use environment variables. There are possibly better solutions but these are two good options. I decided to use a settings file but I'll outline both approaches.
Using A Settings File
Create a file at /etc/your_project_name/settings.ini. The contents of the file will look something like:
[project] SECRET_KEY: your_secret_key [database] DATABASE_ENGINE: your_database_engine DATABASE_USER: your_database_user DATABASE_PASSWORD: your_database_password DATABASE_NAME: your_database_name
In the Django settings.py file include the following code to retrieve information from the newly created settings.ini file:
from configparser import RawConfigParser config = RawConfigParser() config.read('/etc/your_project_name/settings.ini') SECRET_KEY = config.get('project', 'SECRET_KEY')
Using Environment Variables
Using environment variables is also a simple process. Set each environment variable by running the following command from a terminal:
More specifically, to set your project's secret key run the following command:
In the Django settings.py file include the following code to retrieve information from the newly created environment variables:
import os SECRET_KEY = os.environ['SECRET_KEY']
Note: This post was written using Ubuntu 14.04.