How to set up environment variables in Django?

How to set up environment variables in Django?

Setup ".env" files in Django

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 your manage.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 our settings.py file. Note: Keep in mind that this code needs to be put just after your BASE_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 your settings.py file:
import os

FOO = os.getenv("FOO")

For more such crispy blogs, follow DevJunction, subscribe to our newsletter and get notified.