Managing environment variables safely is crucial in every Django project. The
.env file helps us achieve this by keeping our secret configurations separate from the source code. In this guide, we will explore how to use
.env file in Django to manage environment variables.
Installation of Dependencies
To get started, you need to install the
python-dotenv package. These packages make it easy to manage environment variables in Django.
pip install django-environ
pip install python-dotenv
Creation of the.env file
Create a file called
.env in the root directory of your Django project, at the level of your
manage.py 1 file.
settings.py file, import the necessary functions and load the environment variables from the
env = environ.Env()
SECRET_KEY = env('SECRET_KEY')
DEBUG = env.bool('DEBUG', default=False)
DATABASE_URL = env.db('DATABASE_URL')
Access to Environment Variables
You can now access your environment variables in Django using the
Using ".env" files in Django (or any application) is a game changer when it comes to managing settings and configurations. Makes your application more flexible and secure by separating configurations from code. Always remember to protect sensitive information and keep configurations as clear and simple as possible.