Home > OS >  Django set environment variable via command line and use in Migrations
Django set environment variable via command line and use in Migrations

Time:08-09

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.

The .env file holds the database connection information (connection strings).

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

python manage.py migrate

I need to be able to specify which environment I want the migrations to run on.

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

CodePudding user response:

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')

CodePudding user response:

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
  • Related