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?
CodePudding user response:
Your loaded dev.env file does not contain 'DB_NAME' as a key.
CodePudding user response:
I think you got this error because you have not used 'get':
Simply you can try this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASS'),
'HOST': os.environ.get('DB_HOST'),
'PORT': os.environ.get('DB_PORT'),
}
}
And also i changed square brackets to round brackets.
See if this is solves your error