使用Django连接到远程postgres dB时出现问题

使用Django连接到远程postgres dB时出现问题,django,postgresql,digital-ocean,Django,Postgresql,Digital Ocean,无法使用Django连接到我的远程postgres dB。连接细节很好,因为我可以使用我的数据库运行普通的python脚本。但是,通过Django连接会导致此错误= Connecting to the PostgreSQL database... could not connect to server: Connection timed out Is the server running on host "HOSTNAME" ("IP_ADDRESS

无法使用Django连接到我的远程postgres dB。连接细节很好,因为我可以使用我的数据库运行普通的python脚本。但是,通过Django连接会导致此错误=

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?
这很奇怪,因为在我的设置文件中没有创建端口=5432的位置,我还添加了返回到允许主机的IP地址,但仍然没有解决问题。我使用的是数字海洋管理的postgres数据库

这是我的
settings.py
文件=

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',
# )

我如何用Django解决这个问题?谢谢大家!