30

在遵循这些关于添加 env 数据库设置的说明后,我正在尝试让我的本地开发 django 应用程序工作。

https://devcenter.heroku.com/articles/django-injection

我按照说明进行操作,但是当我的应用程序尝试访问本地数据库时出现以下错误

Request Method: GET
Request URL:    http://localhost:8000
Django Version: 1.4
Exception Type: ImproperlyConfigured
Exception Value:    
You need to specify NAME in your Django settings file.

我最初的数据库设置,

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'db',                      # Or path to database file if using sqlite3.
        'USER': 'foo',                      # Not used with sqlite3.
        'PASSWORD': 'bar',                  # Not used with sqlite3.
        'HOST': 'localhost',                
        'PORT': '5432',
    }
}

heroku 文章说将以下内容添加到设置文件中

import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}

当 DATABASE_URL 在 dev 中不可用时,如何让 dj_database_url.config 使用我的 dev 设置?

4

5 回答 5

39

您可以像这样将您的开发设置添加到默认值...

import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://foo:bar@localhost:5432/db')}
于 2012-06-19T11:40:25.797 回答
13

在你的 settings.py 中使用它:

DATABASES = {'default': dj_database_url.config(default=os.environ['DATABASE_URL'])}

在你的 .env 文件中有这个:

DATABASE_URL=postgres://localhost/yourdbname

当您使用“foreman start”启动时,它会查看 .env 文件并创建所有这些环境变量,就像在 Heroku 本身上运行一样。键入“heroku config”以确认您设置了 DATABASE_URL,如果您添加了 postgres 数据库插件,您应该这样做。

于 2012-09-12T15:50:33.313 回答
8

只需在您的操作系统上设置一个环境变量并检查它是否已设置。例如,对于 UNIX 系统:

# In ~/.bash_profile
export LOCAL_DEV=true

# In settings.py
import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}

if bool(os.environ.get('LOCAL_DEV', False)):
    # Override DATABASES['default'] with your local database configuration

此外,如果您需要在 heroku 空间上设置环境变量:

heroku config:add MY_VAR='my_value'
于 2012-06-17T15:20:39.617 回答
5

我刚试过这个,这是我的代码:

import dj_database_url

local_db = 'postgres://django_login:123456@localhost/django_db'
DATABASES = {'default': dj_database_url.config(default=local_db)}

我的数据库名称是“django_db”,用户名是“django_login”,密码是“123456”。

我的代码可以在本地机器和heroku上运行。

于 2012-10-06T09:41:15.763 回答
1

导入 dj_database_url

DATABASES = {'default': dj_database_url.config(default='postgres:// yourusername : yourpassword @ yourhosturl :5432/ yourdbname ')}

** 如果您使用的是本地数据库,请将粗体字符串替换为您的数据库设置,然后将yourhosturl替换为localhost

于 2016-08-29T07:51:33.327 回答