How to set up environment variables in Django?
Setup ".env" files in Django
Play this article
Django does not come with built-in support for dot env(.env
) files. But we have an amazing Python package for that.
- Let’s first install this package in our Django project’s virtual environment.
pip install python-dotenv
- The next step is to create your
.env
files at the root level where yourmanage.py
resides, and define your environment variables similar to the given example below.
FOO="BAR"
- Now just open your Django
settings.py
files and import the package at the top of it.
import dotenv
- It's time to read/parse the
.env
file that we have created above in oursettings.py
file. Note: Keep in mind that this code needs to be put just after yourBASE_DIR
is defined.
import os
import dotenv
dotenv_file = os.path.join(BASE_DIR, ".env")
if os.path.isfile(dotenv_file):
dotenv.load_dotenv(dotenv_file)
- That’s it, now you can simply read your environment variables using
os
library. An example would be like this inside yoursettings.py
file:
import os
FOO = os.getenv("FOO")
For more such crispy blogs, follow DevJunction, subscribe to our newsletter and get notified.
Social Links
- LinkedIn: https://www.linkedin.com/in/mnamegaurav/
- YouTube: https://www.youtube.com/c/devjunction
- Website: https://gaurav.devjunction.in/
- GitHub: https://github.com/mnamegaurav
- Instagram: https://www.instagram.com/mnamegaurav/
- Twitter: https://twitter.com/mnamegaurav