Working with environmental variables in django
87
Introduction
Managing environmental variables is crucial for configuring Django applications across different environments such as development, staging, and production. Environmental variables help keep sensitive information like API keys, database credentials, and secret keys secure while allowing flexibility and scalability in deployment. In this guide, we'll explore how to work with environmental variables in Django using the python-dotenv library.
Prerequisites
Before diving in, ensure you have the following:
- Django Project: A Django project set up and ready for development.
Installation:
Install python-dotenv
using pip:
pip install python-dotenv
Loading the file
At the top of settings.py file, write the following code
import os
from dotenv import load_dotenv
load_dotenv()
Creating the .env file
In your project folder (where manage.py file is located) , create a .env file
and paste the code below
SECRET_KEY=yoursecretkey
replace yoursecretkey with your actual secret key.
Now, let's replace the secret key variable in out settings.py and load it with what we have in our env file
SECRET_KEY = os.environ.get('SECRET_KEY')
Conclusion
Working with environmental variables in Django is a crucial aspect of building web applications. By following the steps outlined in this post, you can manage your application's settings and secrets in your Django projects, ensuring sensitive information remains confidential.