我正在使用Django制作一个Facebook应用程序,并希望在Heroku上部署我的项目。在部署我的项目时,我使用解耦模块将我的重要数据放在。env文件中。我settings.py文件看起来是这样的:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': config('DB_NAME'),
'USER': config('DB_USER'),
'PASSWORD' : config('DB_PASSWORD'),
'HOST' : config('DB_HOST'),
'PORT': '5432',
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
USE_I18N = True
USE_TZ = True
STATIC_URL = 'static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Default primary key field type
和我的。env文件看起来像这样
SECRET_KEY=#####
DB_NAME=#######
DB_USER=########
DB_PASSWORD=#######
DB_HOST=#########
和我面对这个错误:
OperationalError at /login
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
Request Method: POST
Request URL: https://facebook-django-akhil.herokuapp.com/login
Django Version: 4.0.6
Exception Type: OperationalError
Exception Value:
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
Exception Location: /app/.heroku/python/lib/python3.10/site-packages/psycopg2/init.py, line 122, in connect
Python Executable: /app/.heroku/python/bin/python
Python Version: 3.10.5
Python Path:
['/app/.heroku/python/bin',
'/app',
'/app/.heroku/python/lib/python310.zip',
'/app/.heroku/python/lib/python3.10',
'/app/.heroku/python/lib/python3.10/lib-dynload',
'/app/.heroku/python/lib/python3.10/site-packages']
Server time: Thu, 14 Jul 2022 13:44:31 +0000
你还需要创建一个数据库去你的应用程序。因为你已经在使用Heroku,你可以使用Heroku Postgres作为一个应用程序插件。
在免费层为应用程序创建数据库:
heroku addons:create heroku-postgresql:hobby-dev
现在,Heroku将自动为你的应用注入DATABASE_URL
环境变量,所以你需要在你的应用中使用该信息来连接到数据库:
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {
'default': dj_database_url.config()
}
对于您的本地开发环境,您可以从.env
中删除DB_NAME
,DB_USER
和其他DB_XXX
环境变量,并将DATABASE_URL=postgres://username:password@localhost/dbname
添加到.env
中,当然要填写正确的用户名,密码和dbname。