Using Environment Variables in Django
Environment variables are a great way to securely store sensitive information such as API keys, database credentials, and other configuration settings that should not be hardcoded into your Django application's settings.py file. In this article, we'll walk through the process of using environment variables in Django to make your application more secure and flexible.
1. Why Use Environment Variables?
Environment variables allow you to store configuration settings outside your codebase, making your application more portable, secure, and easier to deploy in different environments (e.g., development, testing, production). By using environment variables, you can easily change settings without having to modify your source code.
2. Storing Environment Variables
Environment variables can be set in different ways depending on your operating system and deployment platform. Here are a few common methods:
- Local development (Mac/Linux): You can export environment variables directly in your terminal.
- Local development (Windows): Use the
setcommand in Command Prompt or set environment variables through System Properties. - Using a .env file: You can store environment variables in a
.envfile in your project's root directory (recommended for local development).
3. Using a .env File with Django
One of the most popular ways to manage environment variables in Django is by using a .env file. This file will contain key-value pairs representing your environment variables. To load these variables into your Django settings, we use the python-dotenv package.
Step 1: Install the python-dotenv package
First, install the python-dotenv package, which will help us load variables from the .env file:
pip install python-dotenv
Step 2: Create the .env file
In your project's root directory, create a .env file and add your environment variables. For example:
# .env file
DJANGO_SECRET_KEY="your-secret-key"
DEBUG=False
DATABASE_URL="postgres://user:password@localhost:5432/mydatabase"
In this example, we store the SECRET_KEY, DEBUG flag, and the DATABASE_URL in the .env file. Make sure to never commit this file to version control for security reasons.
Step 3: Load Environment Variables in settings.py
Now, we need to load these environment variables in our settings.py file. We will use python-dotenv to read the variables from the .env file:
import os
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Now you can access the environment variables using os.environ
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
DEBUG = os.environ.get('DEBUG') == 'True' # Convert the string to a boolean
DATABASE_URL = os.environ.get('DATABASE_URL')
The load_dotenv() function loads the variables from the .env file into the environment. Then, you can use os.environ.get() to access the values in your settings file.
4. Using Environment Variables for Database Configuration
It’s common to store database configuration details in environment variables. For example, the DATABASE_URL variable in the .env file contains the credentials for connecting to the database. We can use this variable to configure the Django database settings dynamically:
import dj_database_url
DATABASES = {
'default': dj_database_url.config(default=os.environ.get('DATABASE_URL'))
}
The dj_database_url package is used to parse the DATABASE_URL string and convert it into a dictionary that Django can use to connect to the database. This allows you to configure your database connection using a single environment variable.
5. Using Environment Variables for Secret Keys
For security reasons, it is essential to keep sensitive information such as the Django SECRET_KEY outside the source code. Instead of hardcoding the SECRET_KEY directly in settings.py, we use an environment variable:
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
By loading the SECRET_KEY from an environment variable, you ensure that the key remains secret and does not get exposed in the source code or version control.
6. Using Environment Variables for Debug Mode
In a production environment, you want to disable Django's DEBUG mode. Instead of hardcoding DEBUG=False in your settings, you can use an environment variable to control this setting:
DEBUG = os.environ.get('DEBUG', 'False') == 'True' # Default to False if not set
In the example above, the DEBUG setting is controlled by the DEBUG environment variable. If the variable is not set, it defaults to False.
7. Using Environment Variables for Third-Party API Keys
Another common use case for environment variables is storing third-party API keys. Let’s say you are using the Google Maps API, and you want to store the API key in an environment variable:
GOOGLE_MAPS_API_KEY = os.environ.get('GOOGLE_MAPS_API_KEY')
With this approach, your API keys remain secure and are not exposed in the source code.
8. Best Practices for Managing Environment Variables
- Do not commit your
.envfile to version control (e.g., Git). Add it to your.gitignorefile to ensure it is excluded from commits. - Use different environment variable values for development, staging, and production environments.
- Keep sensitive information, like API keys and passwords, encrypted or managed by a secrets manager if possible.
- Use environment variables for any configuration that is likely to change depending on the deployment environment.
9. Conclusion
Using environment variables in Django allows you to securely store sensitive data and configuration settings outside your codebase. By following the best practices outlined in this article, you can ensure that your Django application is more secure, portable, and easier to deploy across different environments.