In continuation with my previous post on simple Django tips, here is another one. In fact, it's not a tip, it's a mandatory practice that needs to be followed in any Django project.
In any project, many properties should not be visible evidently for security reasons. They should not be checked in code repos either. A few common examples in a Django project are database details, the secret key of a project, email settings, cloud storage details, caching details, ALLOWED_HOSTS, DEBUG and any third-party API keys one may use.
A common approach to handle these is to maintain a
.env file, load the property file using
loaddotenv and fetch the property using
Let's look at the steps to implement this approach. To not repeat myself, I suggest following steps 1 through 4 from my previous post.
Step 1: Install python-dotenv
Per the pypi definition,
python-dotenv reads key-value pairs from a
.env file and use them to set as environment variables.
pip install python-dotenv
Step 2: Create a .env file
At the root level of your project (where
manage.py resides), create a
Step 3: Add entries to
Properties that are not to be made visible and kept secure should be added to the
.env file. To start with, let's just add
SECRET_KEY=<your django project''s secret key> DEBUG=True
Step 4: Import and load
dotenv files in
Once the required properties are set in the
.env file, let's move on to making use of them. Navigate to
base.py and add the following statements
from dotenv import load_dotenv load_dotenv()
Step 5: Fetch properties from
Now that the environment variables are loaded from the file, we can invoke them using the usual
os package like so 👇
# SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get("DEBUG") == "True"
In case of
DEBUG we require a boolean value. Since
os.environ.get always returns a string value, we add the check of
== "True". Otherwise, it will always be true irrespective of the actual value set in the
Step 6: Add
.env file to
This is a very important step. Do not forget to add
.env file to your
.gitignore. Otherwise, it will be added to your code repository thus defeating the whole purpose of keeping things secret.
As the title of the post says, this is a simple tip and hence a short post. Though short, make sure to incorporate this step whenever you build a Django project.