Environmental variables from .env file not available during local migrations in django, heroku
Question: 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?


Answer: `manage.py` doesn't know anything about your .env file. You'll need to run the
command under something that does; either
[Foreman](https://github.com/ddollar/foreman), which is what Heroku itself
uses, or [Honcho](https://github.com/nickstenning/honcho), which is a Python
implementation.

