Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environmental variables from .env file not available during local migrations in django, heroku

I have been developing on Heroku, using the config variables to store sensitive and other environmental variables. While developing locally, I have mirrored these variables in the .env file.

What I am finding now is the variables from the .env file do not load during migrations. They ARE loading while running the local web server with heroku local, but NOT loading for migrations. This was not a problem while my local app was still using the default sqlite3 database, because the sqlite default DB was "hard-coded" in the settings file. However recently I want to use my local Postgresql DB for local dev. OK so I added the DATABASE_URL variable to my .env file.

I cannot get my local app to migrate to the DB. I have found out that this is because the .env file contents are not added to the os.environ mapping duing migrations.

To test, I added a test variable to the .env file:

TEST="teeeest"

Then in settings.py:

import os
import dj_database_url

if "TEST" not in os.environ:
    raise Exception("No .env vars found.")

I tried python manage.py migrate:

File "/Users/apple/heroku/b/b/settings.py", line 16, in raise Exception("No .env vars found.") Exception: No .env vars found.

However I can run heroku local and there is no error. I have also done further testing to ensure that the .env variables ARE available during heroku local.

For various reason I want to set my local DB connection string in the .env file, but doesn't seem possible at the moment. Is this the correct behavior for django on heroku? .env file variables are only accessible when you run the server, and not for migrations?

like image 553
jeffery_the_wind Avatar asked Mar 11 '23 16:03

jeffery_the_wind


2 Answers

I finally figured out that simply running python manage.py migrate did nothing to load the .env file variables. You need to do run the commands in the heroku local environment:

heroku local:run python manage.py migrate

https://devcenter.heroku.com/articles/heroku-local#run-your-app-locally-using-the-heroku-local-command-line-tool-run-a-one-off-command-locally

like image 69
jeffery_the_wind Avatar answered Mar 25 '23 03:03

jeffery_the_wind


manage.py doesn't know anything about your .env file. You'll need to run the command under something that does; either Foreman, which is what Heroku itself uses, or Honcho, which is a Python implementation.

like image 25
Daniel Roseman Avatar answered Mar 25 '23 02:03

Daniel Roseman