【问题标题】:django - error adding database to herokudjango - 将数据库添加到heroku时出错
【发布时间】:2018-02-26 15:04:38
【问题描述】:

我正在努力在 heroku 上部署我的应用程序。主要是数据库配置问题。

这是settings.py文件的底部,

import dj_database_url

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

try:
    from .local_settings import *
except ImportError:
    pass

这是我的 local_settings.py 文件,

导入操作系统 BASE_DIR = os.path.dirname(os.path.dirname(文件))

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'test',
        'USER': 'test',
        'PASSWORD': 'postgres',
        'HOST': 'localhost',
        'PORT': 5432,
    }  
}

我可以成功运行heroku local web。

但是当我运行时,heroku run python manage.py migrate,它给了我错误,

django.db.utils.OperationalError: could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

当我跑步时,heroku run python manage.py shell,

然后运行

>>> import dj_database_url
>>> dj_database_url.config()

我得到了字典,提供了有关数据库的完整信息。

问题出在哪里?

【问题讨论】:

    标签: python django heroku


    【解决方案1】:

    不应部署您的 local_settings 文件。它仅供本地使用,因此得名。您应该将其从您的 git 存储库中排除。

    【讨论】:

    • 为什么不应该部署它?
    • 因为它是供本地使用的。正如另一个答案所说,它覆盖了生产数据库设置,从而删除了 dj_database_url 东西的全部内容。
    【解决方案2】:

    尝试先从local_settings.py 导入设置,然后更改DATABASES 设置,

    import dj_database_url
    try:
        from .local_settings import *
    except ImportError:
        pass
    
    DATABASES = { 'default': dj_database_url.config() }
    

    您在文件中定义了一个DATABASES 变量,但是当您导入local_settings.py 时,您的DATABASES 配置将被开发值覆盖。您应该先进行导入,然后更改 DATABASES 选项。

    就个人而言,我建议您保留base_settings.py 以包含除数据库以外的所有设置,然后将其导入heroku_settings.py,而不是导入整个local_settings。

    保留base_settings、development_settings、heroku_settings(或 production_settings)可以更轻松地处理部署。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      • 1970-01-01
      • 2016-03-09
      • 2014-01-08
      • 1970-01-01
      • 2020-11-08
      相关资源
      最近更新 更多