Django set environment variable via command line and use in Migrations

Following on from this question - Specify a .env file in Django in command line or vscode launch.json. So we have an environment file for dev, test, and production - which is specified in an environment variable ENVIRONMENT_FILE. This holds the database connection information.

However, I'm struggling to pass this information when running the migration command:

python manage.py migrate

Is it possible to setup environment variables before migrations can be run?

You can load in the environment variables in your settings.py file.

If you have separate .env files for separate environments, and it is managed by the ENVIRONMENT_FILE variable, you can use something like python-dotenv to read your env files,

import os
from dotenv import load_dotenv

load_dotenv(os.getenv("ENVIRONMENT_FILE", ".env"))

Then, if your env file looks like this

DATABASE_URL=some-url-over-here

you can access these anywhere in your django application using os.getenv('DATABASE_URL')

You can set environment variables before you run the migration command. In PowerShell you can do something like:

$env:ENVIRONMENT_FILE='test.env'
python manage.py migrate
Back to Top