I am developing an app in django and I pushed it on Heroku.
I want to query my database with SQL in my views.py, so I connect to my database with connect
method.
When it comes to deploying my app, I obviously want to hide my database credentials.
So I save them in a .env
file in root directory and use the config
function to call these variables from my views.py.
However, I run into:
VIEW_DB_USER not found. Declare it as envvar or define a default value.
(error at view_db_user = config("VIEW_DB_USER")
)
Here is my views.py:
import os
import django_heroku
from decouple import config
import dj_database_url
view_db_user = config("VIEW_DB_USER")
view_db_password = config("view_db_password")
view_db_host = config("view_db_host")
view_db_database = config("view_db_database")
mydb = pg2.connect(user=VIEW_DB_USER, password=view_db_password,
host=view_db_host, database=view_db_database)
Here is my .env
file:
SECRET_KEY = 'credential_1'
VIEW_DB_USER = 'credential_2'
view_db_password = 'credential_3'
view_db_host = 'credential_4'
view_db_database = 'credential_5'
From what I see, the problem is that the function config
is somehow not working properly. But why?
Please note that this does not work both in local and on heroku.
Also note that SECRET_KEY contains a password of another database that perfectly works, being this passwork stored in my .env
file.
SOLVED:
First problem was the columns in the .env
file.
With the following fix, it works perfectly in local, while on Heroku I still got the same error:
SECRET_KEY = 'credential_1'
VIEW_DB_USER = credential_2
view_db_password = credential_3
view_db_host = credential_4
view_db_database = credential_5
This was because I forgot to add the environment variables in Heroku Config Vars section
See this tutorial at paragraph "deploying to Heroku"