env.py

What Is The env.py File?

When developing with Django, it's best practice to keep all your sensitive information such as secret keys, database credentials, and API keys out of your source code to maintain a good level of security. An env.py file is the most common way to manage these values by storing them as environment variables that your Django project can securely access. The purpose of this is to improve security by keeping sensitive information out of your source code and prevent accidental exposure of credentials when sharing or publishing your project. It is amazing how many credentials are accidentally leaked through public repositories.

A Typical env.py File

By default there is no env.py file in a Django project so you will need to create one in your root directory and then !!! IMMEDIATELY ADD IT TO YOUR .gitignore FILE !!!

At the top of your env.py file you will need to import os in order to manipulate your variables. Then for each variable you want to keep secret you will need to create them using the following syntax:

os.environ["SECRET_VARIABLE_NAME"] = "secret-variable-value"

A key variable to include here would be:

os.environ["DEVELOPMENT"] = "On"

This will let you to create a check in your settings.py file, keeping your project in development mode when working locally but when it is hosted it will automatically exit developer mode.

For Django projects you will also typically include a SECRET_KEY and other key information for your project. This might include a database (name, username, and password), API keys, email service credentials, or cloud storage credentials.

For this project mine looks like:

# Website link: https://webdevgrad-.herokuapp.com/
import os

os.environ["SECRET_KEY"] = ('whatever-your-secret-key-is')
os.environ["DEVELOPMENT"] = "On"
os.environ["ALGOLIA_APP_ID"] = "value"
os.environ["ALGOLIA_SEARCH_KEY"] = "value"
os.environ["ALGOLIA_WRITE_KEY"] = "value"

Getting these variables in your settings.py file from your env.py file is outline here on the settings.py page.