Forums

How to set up loading environment variables to also work for local development

The official Guide on this topic explains well how to set up environment variables in the production environment on Pythonanywhere by loading them in the WSGI file.

What I didn't understand was how can I make the environment variables at the same time work in my local environment?

Here is my setup:

# production .env
export SECURE_KEY=mysecretkey

# development .env
export DEBUG=True

In the settings.py:

# settings.py
...
import os
from dotenv import load_dotenv

load_dotenv(BASEDIR / '.env')

SECRET_KEY = os.getenv("SECRET_KEY", default="fallbacksecretkey")
DEBUG = os.getenv("DEBUG", default=False)

However doing that would mean (if i understand correctly) that in the production environment the variables get loaded twice (in the WSGI file AND in the settings.py). What would be the best approach here to avoid that?

In wsgi file, you populate your environment variables, in the setting you use them to configure your Django.

On your local machine, you need to set variables before running the dev server.