Warm tip: This article is reproduced from stackoverflow.com, please click
credentials django environment-variables connect decoupling

Django can't find my environment variable? VIEW_DB_USER not found. Declare it as envvar or define a

发布于 2020-03-31 22:56:42

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.

Questioner
Tms91
Viewed
130
Tms91 2020-02-01 08:04

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

https://dashboard.heroku.com/apps/my_app_name/settings

See this tutorial at paragraph "deploying to Heroku"