I am making a Facebook app using Django and want to deploy my project on Heroku. While deploying my project I am putting my important data in a .env file using decouple module. My settings.py file looks like this:
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
and my .env file looks like this
SECRET_KEY=#####
DB_NAME=#######
DB_USER=########
DB_PASSWORD=#######
DB_HOST=#########
and I am facing this error:
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
CodePudding user response:
You need to also create a database to go with your app. Since you're already using Heroku, you can use Heroku Postgres as an app addon.
To create the database for your app on the free tier:
heroku addons:create heroku-postgresql:hobby-dev
Now, Heroku will automatically inject the DATABASE_URL
environment variable for your app, so you'll need to use that information in your app to connect to the database:
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {
'default': dj_database_url.config()
}
For your local development environment, you can remove DB_NAME
, DB_USER
and the other DB_XXX
environment variables from your .env
and add DATABASE_URL=postgres://username:password@localhost/dbname
to your .env
instead, filling in the correct username, password, and dbname, of course.