visit
More often than not, I see many of my software engineer friends miss a couple of key points when developing Django projects, and that is, not hiding their SECRET_KEY and other OAuth keys. This is a crucial part of the security of Django as any information exposed can revoke a project.
Let's begin. Suppose we have just started a brand new Django project. Just in case, here is the format:django-admin startproject project
Now that we have created a new project, let's navigate into the root directory, that being project/, and into the settings.py file.
On the 23rd line of the code, you will find a variable titled SECRET_KEY.
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname...
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ek0@9u(zemu^+%*-z3!&y9mu_7u+edg9%)c%423mdoec-mi*'
pip3 install python-dotenv
Next, in your settings.py file, C & V (copy and paste) the following two lines:
from dotenv import load_dotenv
load_dotenv()
Afterward, in the root of your project, create a file titled .env which will serve as your environment variable secret storage for your project.
In the .env, you will declare your variables with an = sign and paste their information as such:
# .env
SECRET_KEY=ek0@9u(zemu^+%*-z3!&y9mu_7u+edg9%)c%423mdoec-mi*
Next, in your settings.py, you will retrieve the key as follows:
# settings.py
SECRET_KEY = str(os.getenv('SECRET_KEY'))
What this line does is make the os (operating system) get the .env file and bring in the data for the following key: SECRET_KEY.
To ensure no one receives access to the .env file, it is a general protocol to put your .env file in the .gitignore to make sure it won't be committed to GitHub.
If you were using any other keys, such as OAuth keys, the method would work the same. For example, here I will implement an OAuth key to use the Twitter OAuth method.# settings.py
TWITTER_OAUTH_KEY = str(os.getenv('TWITTER_OAUTH_KEY'))
# .env
TWITTER_OAUTH_KEY=[twitter-oauth-key-here]
Also published at