ladbrook
ladbrook

Reputation: 11

Problem when trying to migrate command in Django app on Heroku server

I am currently trying to deploy my Django project on to a free Heroku server. When I try to execute the following command I get an error heroku run python3 manage.py migrate. The error is as follows:

Running python3 manage.py makemigrations on ⬢ samstaskmanager... up, run.5214 (Free)
Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
    self.connect()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 200, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
    connection = Database.connect(**conn_params)
  File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.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?


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 85, in wrapped
    res = handle_func(*args, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle
    loader.check_consistent_history(connection)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/loader.py", line 290, in check_consistent_history
    applied = recorder.applied_migrations()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
    if self.has_table():
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 55, in has_table
    with self.connection.cursor() as cursor:
  File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 259, in cursor
    return self._cursor()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 235, in _cursor
    self.ensure_connection()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
    self.connect()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
    self.connect()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 200, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
    connection = Database.connect(**conn_params)
  File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
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?

This is my settings.py:

Django settings for app project.

Generated by 'django-admin startproject' using Django 3.1.1.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path
import os
#import django_heroku


# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'x0)a5try9uyd+t_l-5x#1*yfu@-$-(u665rz5@_m!!t5b7&d(6'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'taskmanager.apps.TaskmanagerConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'app.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'app.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'taskmanager',
        'USER': 'postgres',
        'PASSWORD': 'sam3778987',
        'HOST': 'localhost'
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

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',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'


STATIC_ROOT = os.path.join(BASE_DIR, 'static')


# Activate Django-Heroku.
#django_heroku.settings(locals())

I am really not sure why I keep getting this error so any help would be appreciated. Also sorry about the messy question it is my first time writing one.

Upvotes: 1

Views: 772

Answers (2)

James Tollefson
James Tollefson

Reputation: 893

Looks to me like you are trying to use a PostgreSQL database on your local machine with your app hosted on Heroku.

I use a PostgreSQL database on a recently created app. I eventually created two settings.py files (with different names, obviously). One is what I use when I run the app locally. It has the following code for the database connection:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': DB_NAME,
        'USER': MY_USERNAME,
        'PASSWORD': MY_PASSWORD,
        'HOST': HOST,
        'PORT': '5432',
    }
}

In my production settings.py (which I call settings_heroku_deploy.py and use in my Procfile during deployment) I have the following:

import dj_database_url
DATABASES = {}
DATABASES['default'] = dj_database_url.config(conn_max_age=600)
DATABASES['default']['ENGINE'] = 'django.db.backends.postgresql'

You probably know this already, but one of the characteristics of a PostgreSQL database is that it's hosted on a server. So the server you use needs to be available wherever you happen to run your application. I chose to configure a PostgreSQL database as an addon in Heroku. During deployment I use the dj_database_url package to automatically configure my connection, whereas on my local machine I have to explicitly provide username, password, etc.

Even if you can get your app to connect to your local database it's definitely worth making the switch a Heroku PostgreSQL database. It's free to start and certainly more flexible than hosting something locally (unless you have an actual server at your disposal).

Upvotes: 1

Deepak Raj
Deepak Raj

Reputation: 501

It's due to your Postgres database.you can find it in the settings.py. change the host and port setting. maybe you have blank the host and port section. Let me know if it helps you.


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

edit: Thanks for sharing your settings.py code. Let me know if it helps you.

Upvotes: 0

Related Questions