Question

Trouble connecting to my managed postgres dB using Django

Having trouble connecting to my Digital Ocean Managed Postgres dB using Django. My connection details are correct because I can run normal python scripts that connect to my dB just fine. However, connecting via Django causes this error:

Connecting to the PostgreSQL database...
could not connect to server: Connection timed out
        Is the server running on host "HOSTNAME" ("IP_ADDRESS") and accepting
        TCP/IP connections on port 5432?

I don’t know which the error returns port 5432, which is the default postgres port. In my settings file I only inputted my DO port.

Here is my settings.py file

import os
from pathlib import Path
from urllib.parse import urlparse
import dj_database_url
import logging.config

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

BASE_DIR = os.path.dirname(os.path.abspath(__file__))


# 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 = os.environ.get('SECRET_KEY_DJANGO')


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

ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'home.apps.HomeConfig',
    'django_plotly_dash.apps.DjangoPlotlyDashConfig',
    'dpd_static_support',
    'channels',
    'channels_redis',
    'bootstrap4',
    'blog',
]

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            'hosts': [('127.0.0.1', 6379),],
        },
    },
}

MIDDLEWARE = [

      'django.middleware.security.SecurityMiddleware',

      'whitenoise.middleware.WhiteNoiseMiddleware',

      'django.contrib.sessions.middleware.SessionMiddleware',
      'django.middleware.common.CommonMiddleware',
      'django.middleware.csrf.CsrfViewMiddleware',
      'django.contrib.auth.middleware.AuthenticationMiddleware',
      'django.contrib.messages.middleware.MessageMiddleware',

      'django_plotly_dash.middleware.BaseMiddleware',
      'django_plotly_dash.middleware.ExternalRedirectionMiddleware',

      'django.middleware.clickjacking.XFrameOptionsMiddleware',

  ]

ROOT_URLCONF = 'stockbuckets.urls'



TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['stockbuckets/templates', 'home/templates', 'blog/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',
            ],
        },
    },
]

X_FRAME_OPTIONS = 'SAMEORIGIN'


WSGI_APPLICATION = 'stockbuckets.wsgi.application'


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.environ.get('DO_DB'),
        'USER' : os.environ.get('DB_USER'),
        'PASSWORD' : os.environ.get('DB_PASSWORD'),
        'HOST' : os.environ.get('DB_HOST'),
        'PORT' : os.environ.get('DB_PORT')
    }
}


db_from_env = dj_database_url.config(conn_max_age=600)
DATABASES['default'].update(db_from_env)

# 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


CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient"
        },
        "KEY_PREFIX": "example"
    }
}

PLOTLY_DASH = {
    #"ws_route" : "ws/channel",

    #"insert_demo_migrations" : True,  # Insert model instances used by the demo

    #"http_poke_enabled" : True, # Flag controlling availability of direct-to-messaging http endpoint

    "cache_timeout_initial_arguments": 60,

    #"view_decorator" : None, # Specify a function to be used to wrap each of the dpd view functions

    "cache_arguments" : True, # True for cache, False for session-based argument propagation

    #"serve_locally" : True, # True to serve assets locally, False to use their unadulterated urls (eg a CDN)

    #"stateless_loader" : "demo.scaffold.stateless_app_loader",
    }


STATICFILES_LOCATION = 'static'
STATIC_URL = '/static/'

# STATIC_ROOT = os.path.join(BASE_DIR,'static')
# STATICFILES_DIRS = [
#     os.path.join(BASE_DIR, 'stockbuckets/static')
# ]

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

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'


CRISPY_TEMPLATE_PACK = 'bootstrap4'

ASGI_APPLICATION = 'stockbuckets.routing.application'

CHANNEL_LAYERS = {
    'default' : {
        'BACKEND': 'channels_redis_core.RedisChannelLayer',
        'CONFIG' : {
            'hosts' : [('127.0.0.1',6379),],
        }
    }

}

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

    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',

    'django_plotly_dash.finders.DashAssetFinder',
    'django_plotly_dash.finders.DashComponentFinder',
    'django_plotly_dash.finders.DashAppDirectoryFinder',
]

PLOTLY_COMPONENTS = [

    # Common components
    'dash_core_components',
    'dash_html_components',
    'dash_renderer',

    # django-plotly-dash components
    'dpd_components',
    # static support if serving local assets
    'dpd_static_support',

    # Other components, as needed
    'dash_bootstrap_components',
    
]

# Configure Django App for Heroku.
import django_heroku
django_heroku.settings(locals())

# Logging Configuration

# Clear prev config
# LOGGING_CONFIG = None

# # Get loglevel from env
# LOGLEVEL = os.getenv('DJANGO_LOGLEVEL', 'info').upper()

# logging.config.dictConfig({
#     'version': 1,
#     'disable_existing_loggers': False,
#     'formatters': {
#         'console': {
#             'format': '%(asctime)s %(levelname)s [%(name)s:%(lineno)s] %(module)s %(process)d %(thread)d %(message)s',
#         },
#     },
#     'handlers': {
#         'console': {
#             'class': 'logging.StreamHandler',
#             'formatter': 'console',
#         },
#     },
#     'loggers': {
#         '': {
#             'level': LOGLEVEL,
#             'handlers': ['console',],
#         },
#     },
# })




# STATIC_URL = '/static/'
# STATIC_ROOT = Path(BASE_DIR).joinpath('staticfiles')
# STATICFILES_DIRS = (Path(BASE_DIR).joinpath('static'),)




# STATIC_URL = '/static/'
# STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
# VENV_PATH = os.path.dirname(BASE_DIR)
# STATIC_ROOT = os.path.join(VENV_PATH, 'static_root')

# Additional locations of static files
# STATICFILES_DIRS = (
#     # Put strings here, like "/home/html/static" or "C:/www/django/static".
#     # Always use forward slashes, even on Windows.
#     # Don't forget to use absolute paths, not relative paths.
#     os.path.join(BASE_DIR, 'static'),
# )

# STATICFILES_FINDERS = (
#     'django.contrib.staticfiles.finders.FileSystemFinder',
#     'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#     # django.contrib.staticfiles.finders.DefaultStorageFinder',
# )

Please let me know how I can connect to my dB through django, many thanks in advance for any guidance or help.

Subscribe
Share

Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hi @ajaramillocastro,

The Postgres Managed database port is 25060; If you are seeing the error on port 5432 means this port has been mentioned on the configuration file.

I would suggest you recheck the Postgres connection configuration details made and see if all details are correct and make sure you have added a trusted source entry of the Django server.

https://docs.digitalocean.com/products/databases/postgresql/how-to/connect/#connection-details

For more information on Postgres managed database connection issues and resolution check the below link:

https://docs.digitalocean.com/products/databases/postgresql/resources/troubleshoot-connections/#connection-timed-out

Regards, Rajkishore