skip to Main Content

I store all my secrets and database params in the dev.env file.
I have 3 different settings files – base, dev and prod.
There is an SQLite database in base, and I want to connect to Postgres in dev.

So I upload my secrets with the environment variable in my dev setting file like this:

from dotenv import load_dotenv
load_dotenv(os.environ.get('ENV_CONFIG', ''))

And I override my database settings in dev settings file:

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ['DB_NAME'],
        'USER': os.environ['DB_USER'],
        'PASSWORD': os.environ['DB_PASS'],
        'HOST': os.environ['DB_HOST'],
        'PORT': os.environ['DB_PORT'],
    }
}

But when I run makemigrations with dev settings file:

./manage.py makemigrations --settings=app.settings.dev

I get an error:

File "/Users/admin/Desktop/Programming/Python/UkranianFunds/src/app/settings/dev.py", line 35, in <module>
    'NAME': os.environ['DB_NAME'],
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'DB_NAME'

I checked and my secret with the key DB_NAME clearly appears in the settings file – I printed it successfully. The name of the database is correct.

What are other reasons that cause that?

2

Answers


  1. Chosen as BEST ANSWER

    I solved it by replacing os.environ['DB_NAME'] to os.environ.get('DB_NAME').

    Weird situation for me because the problem occurred only when I did makemigrations.

    After I migrated to Postgres, I tried to run the app with os.environ['DB_NAME'] and it worked fine.

    So it seems that the KeyError is being raised only during makemigrations.


  2. Your loaded dev.env file does not contain ‘DB_NAME’ as a key.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search