简体   繁体   中英

Connect Django to live Heroku Postgres database

I've added a Postgres database to my Heroku app, and am trying to connect my Django app to it. However, my app always connects to the local Postgres database instead.

settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'app_db',
        'USER': 'admin',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '',
    }
}

db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

I've set 'DATABASE_URL' in the .env file to be the url for the Postgres database on my Heroku app, but it doesn't seem to update the database. How do I force my app to connect to the Heroku database rather than the local one?

You can set up your settings to read from your local DB when in development and use your Heroku DB in production. First of all, as you may already know, you need dj_database_url .

You can make a seperate settings file called local_settings.py and in there include your normal db config (eg the default Django db config). And in your settings.py :

DATABASES = {
    'default': dj_database_url.config()
}

And at the bottom of your settings.py :

# Tries to import local settings, if on dev, 
# import everything in local_Settings, which overrides the dj_database_url
# If on deploy, local_settings won't be found so just ignore the ImportError
try:
    from .local_settings import *
except ImportError:
    pass

So your local_settings.py should be in your development server, not in Heroku app (you can ignore it adding it to .gitignore). I hope this is understandable.

Connect to Live heroku DB from local Django code without having to manually set the DATABASE_URL env variable:

Put following code in your settings.py file

import os, subprocess, dj_database_url

bashCommand = “heroku config:get DATABASE_URL -a app_name” #Use your app_name

output = subprocess.check_output([‘bash’,’-c’, bashCommand]).decode(“utf-8”) # executing the bash command and converting byte to string

DATABASES[‘default’] = dj_database_url.config(default=output,conn_max_age=600, ssl_require=True) #making connection to heroku DB without having to set DATABASE_URL env variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM