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 migrate

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

You can load in the environment variables in your 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


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:

python migrate
Back to Top