Home>

Because "Verifying deploy ... done." is displayed in git push heroku main
I think that push is done normally.
After that, when "hroku run python manage.py migrate" is executed, django.db.utils.OperationalError occurs and migration cannot be completed.
Looking at the contents of the error, there was also psycopg2.OperationalError.
Is there something missing between pushing to heroku and migrating?
Is there something wrong with settings.py?
I searched on google, but I couldn't figure out how to solve it, so please let me know.

↓ Reference site
https://qiita.com/hagyyyy1992/items/466b5bab67118175be65

execution result of hroku run python manage.py migrate

Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line
216, in ensure_connection
    self.connect ()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line
194, in connect
    self.connection = self.get_new_connection (conn_params)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py",
 line 168, in get_new_connection
    connection = Database.connect (** conn_params)
  File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in con
nect
    conn = _connect (dsn, connection_factory = connection_factory, ** kwasync)
psycopg2.OperationalError: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "manage.py", line 21, in<module>  main ()
  File "manage.py", line 17, in main
    execute_from_command_line (sys.argv)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", li
ne 371, in execute_from_command_line
    utility.execute ()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", li
ne 365, 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 2
88, in run_from_argv
    self.execute (* args, ** cmd_options)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 3
35, in execute
    output = self.handle (* args, ** options)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate
.py ", line 77, in handle
    connection.prepare_database ()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/gis/db/backends/postgis/
base.py ", line 25, in prepare_database
    with self.cursor () as cursor:
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line
255, in cursor
    return self._cursor ()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line
232, in _cursor
    self.ensure_connection ()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line
216, in ensure_connection
    self.connect ()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit
__
    raise dj_exc_value.with_traceback (traceback) from exc_valueFile "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line
216, in ensure_connection
    self.connect ()
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line
194, in connect
    self.connection = self.get_new_connection (conn_params)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py",
 line 168, in get_new_connection
    connection = Database.connect (** conn_params)
  File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in con
nect
    conn = _connect (dsn, connection_factory = connection_factory, ** kwasync)
django.db.utils.OperationalError: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
Corresponding source code
import os
from django.contrib import admin
### admin screen display settings
admin.AdminSite.site_title ='Login'
admin.AdminSite.site_header ='Administrative screen'
admin.AdminSite.index_title ='Menu'
### Login related
LOGIN_URL ='/ accounts/login' #<-Login URL
LOGIN_REDIRECT_URL ='/' #<-Redirect to top page after login
LOGOUT_REDIRECT_URL ='/' #<-Redirect to top page after logout
##### GDAL error avoidance required for windows
if os.name =='nt':
    import platform
    POSTGRES = r "C: \ Program Files \ PostgreSQL \ 9.6"
    OSGEO4W = r "C: \ OSGeo4W"
    if '64' in platform.architecture () [0]:
        OSGEO4W + = "64"
    assert os.path.isdir (OSGEO4W), "Directory does not exist:" + OSGEO4W
    os.environ ['OSGEO4W_ROOT'] = OSGEO4W
    os.environ ['POSTGRES_ROOT'] = POSTGRES
    os.environ ['GDAL_LIBRARY_PATH'] = OSGEO4W + r "\ bin"
    os.environ ['GEOS_LIBRARY_PATH'] = OSGEO4W + r "\ bin"
    os.environ ['GDAL_DATA'] = OSGEO4W + r "\ share \ gdal"
    os.environ ['PROJ_LIB'] = OSGEO4W + r "\ share \ proj"
    os.environ ['PATH'] = OSGEO4W + r "\ bin;" + POSTGRES + r "\ bin;" + os.environ ['PATH']
#####
# Build paths inside the project like this: os.path.join (BASE_DIR, ...)
BASE_DIR = os.path.dirname (os.path.dirname (os.path.abspath (__ file__)))
# Quick-start development settings --unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '118 # 9w_tjpu ^ (3kq1 # 2f356&% t-h6&^ o $ugxlqt ^ br ^ 2ei_3j ('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False #True
ALLOWED_HOSTS = [
    "*"
]

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',
    Added'whitenoise.middleware.WhiteNoiseMiddleware', #heroku
]
ROOT_URLCONF ='geodj.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 ='geodj.wsgi.application'

#Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE':'django.contrib.gis.db.backends.postgis',
        'NAME':'geodjangodb2',
        'USER':'geo_admin',
        'PASSWORD':'geoadmin',
        'HOST':'localhost',
        'PORT': '5432', #heroku
    },


}
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.templatetags.static',
    'django.contrib.gis',
    'django_cleanup.apps.CleanupConfig', # django-cleanup
    'map.apps.MapConfig',
    'geodj',
    'leaflet',
    'six',
    'django_filters',
    'rest_framework',
    'rest_framework_gis',
    'markdown',
    'PIL',
    'PIL.ExifTags',
]
#Password validation
# https://docs.djangoproject.com/en/3.0/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.0/topics/i18n/
LANGUAGE_CODE ='ja-JP'
TIME_ZONE ='Asia/Tokyo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
#Time out 10 hours after login
SESSION_COOKIE_AGE = 36000
#Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL ='/ static /'
STATIC_ROOT = os.path.join (BASE_DIR,'static')
STATICFILES_DIRS = (os.path.join (BASE_DIR,'map/static'),)
# ↓ heroku added
STATICFILES_STORAGE ='whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_ROOT = os.path.join (BASE_DIR,'media')
MEDIA_URL ='/ media /'
For #heroku
try: try:
    from .local_settings import *
except ImportError:
    pass
if not DEBUG:
    import django_heroku
    django_heroku.settings (locals ())
    import dj_database_url
    DATABASES ['default'] = dj_database_url.config ()
    DATABASES ['default'] ['ENGINE'] ='django.contrib.gis.db.backends.postgis'
    GDAL_LIBRARY_PATH = os.getenv ('GDAL_LIBRARY_PATH')
    GEOS_LIBRARY_PATH = os.getenv ('GEOS_LIBRARY_PATH')
# ~ For heroku
What I tried

Fixed blank to 5432 in DATABASE PORT of settings.py.
Since postgis was not installed, create extension postgis was executed.
I get the same error when I do the above.

When I python manage.py runserver locally, I got the same error.
Add try: ~ except ImportError: pass for heroku at the end of settings.py
You can run server by commenting it out.
That means how to divide settings.py between production and local,
Does it mean something is wrong?

Supplementary information (FW/tool version, etc.)

windows10
django 2.0.8
python 3.6.10

  • Answer # 1

    settings
    "" "
    try: try:
        from .local_settings import *
    except ImportError:
        pass
    "" "


    After commenting out, I was able to migrate.
    When settings.py is divided into production (settings.py) and local (local_settings.py)
    It seems that the method was wrong.
    But I got a server error (500) on heroku open ...