1
votes

I'm having this Connection error deploying my django app on Heroku:

ConnectionError at /admin/login/

HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /authentication/login/ (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 111] Connection refused',))

Exception Value:

HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /authentication/login/ (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 111] Connection refused',))

It seems that the app doesn't find the url where the login must be done but the file setings.py is correct:

"""
Django settings for decide project.

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

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

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

import os
import django_heroku

# 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/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'some secret key'

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

ALLOWED_HOSTS = []


# Application definition

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

    'corsheaders',
    'django_filters',
    'rest_framework',
    'rest_framework.authtoken',
    'rest_framework_swagger',
    'gateway',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.QueryParameterVersioning'
}

AUTHENTICATION_BACKENDS = [
    'base.backends.AuthBackend',
]

MODULES = [
    'authentication',
    'base',
    'booth',
    'census',
    'mixnet',
    'postproc',
    'store',
    'visualizer',
    'voting',
]

#BASEURL = 'http://localhost:8000'
BASEURL = 'https://decide-zapdos-votacion.herokuapp.com'

APIS = {
    'authentication': BASEURL,
    'base': BASEURL,
    'booth': BASEURL,
    'census': BASEURL,
    'mixnet': BASEURL,
    'postproc': BASEURL,
    'store': BASEURL,
    'visualizer': BASEURL,
    'voting': BASEURL,
}

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 = 'decide.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'decide.wsgi.application'


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

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


# Password validation
# https://docs.djangoproject.com/en/2.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/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'

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

STATIC_URL = '/static/'

# number of bits for the key, all auths should use the same number of bits
KEYBITS = 256

# Versioning
ALLOWED_VERSIONS = ['v1', 'v2']
DEFAULT_VERSION = 'v1'

try:
    from local_settings import *
except ImportError:
    print("local_settings.py not found")

# loading jsonnet config
if os.path.exists("config.jsonnet"):
    import json
    from _jsonnet import evaluate_file
    config = json.loads(evaluate_file("config.jsonnet"))
    for k, v in config.items():
        vars()[k] = v


INSTALLED_APPS = INSTALLED_APPS + MODULES
django_heroku.settings(locals())

Full traceback

Environment:


Request Method: POST
Request URL: http://decide-zapdos-votacion.herokuapp.com/admin/login/?next=/admin/

Django Version: 2.0
Python Version: 3.6.9
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'corsheaders',
 'django_filters',
 'rest_framework',
 'rest_framework.authtoken',
 'rest_framework_swagger',
 'gateway',
 'authentication',
 'base',
 'booth',
 'census',
 'mixnet',
 'postproc',
 'store',
 'visualizer',
 'voting']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
 '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')



Traceback:

File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connection.py" in _new_conn
  141.                 (self.host, self.port), self.timeout, **extra_kw)

File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/util/connection.py" in create_connection
  83.         raise err

File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/util/connection.py" in create_connection
  73.             sock.connect(sa)

During handling of the above exception ([Errno 111] Connection refused), another exception occurred:

File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connectionpool.py" in urlopen
  601.                                                   chunked=chunked)

File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connectionpool.py" in _make_request
  357.             conn.request(method, url, **httplib_request_kw)

File "/app/.heroku/python/lib/python3.6/http/client.py" in request
  1254.         self._send_request(method, url, body, headers, encode_chunked)

File "/app/.heroku/python/lib/python3.6/http/client.py" in _send_request
  1300.         self.endheaders(body, encode_chunked=encode_chunked)

File "/app/.heroku/python/lib/python3.6/http/client.py" in endheaders
  1249.         self._send_output(message_body, encode_chunked=encode_chunked)

File "/app/.heroku/python/lib/python3.6/http/client.py" in _send_output
  1036.         self.send(msg)

File "/app/.heroku/python/lib/python3.6/http/client.py" in send
  974.                 self.connect()

File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connection.py" in connect
  166.         conn = self._new_conn()

File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connection.py" in _new_conn
  150.                 self, "Failed to establish a new connection: %s" % e)

During handling of the above exception (<urllib3.connection.HTTPConnection object at 0x7f2e451b9c18>: Failed to establish a new connection: [Errno 111] Connection refused), another exception occurred:

File "/app/.heroku/python/lib/python3.6/site-packages/requests/adapters.py" in send
  440.                     timeout=timeout

File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connectionpool.py" in urlopen
  639.                                         _stacktrace=sys.exc_info()[2])

File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/util/retry.py" in increment
  388.             raise MaxRetryError(_pool, url, error or ResponseError(cause))

During handling of the above exception (HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /authentication/login/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f2e451b9c18>: Failed to establish a new connection: [Errno 111] Connection refused',))), another exception occurred:

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/sites.py" in login
  398.         return LoginView.as_view(**defaults)(request)

File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in view
  69.             return self.dispatch(request, *args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
  62.             return bound_func(*args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
  76.             return view(request, *args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
  58.                 return func.__get__(self, type(self))(*args2, **kwargs2)

File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
  62.             return bound_func(*args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
  142.                     response = view_func(request, *args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
  58.                 return func.__get__(self, type(self))(*args2, **kwargs2)

File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
  62.             return bound_func(*args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
  58.                 return func.__get__(self, type(self))(*args2, **kwargs2)

File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/views.py" in dispatch
  65.         return super().dispatch(request, *args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
  89.         return handler(request, *args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/edit.py" in post
  141.         if form.is_valid():

File "/app/.heroku/python/lib/python3.6/site-packages/django/forms/forms.py" in is_valid
  179.         return self.is_bound and not self.errors

File "/app/.heroku/python/lib/python3.6/site-packages/django/forms/forms.py" in errors
  174.             self.full_clean()

File "/app/.heroku/python/lib/python3.6/site-packages/django/forms/forms.py" in full_clean
  377.         self._clean_form()

File "/app/.heroku/python/lib/python3.6/site-packages/django/forms/forms.py" in _clean_form
  404.             cleaned_data = self.clean()

File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/forms.py" in clean
  195.             self.user_cache = authenticate(self.request, username=username, password=password)

File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/__init__.py" in authenticate
  70.             user = _authenticate_with_backend(backend, backend_path, request, credentials)

File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/__init__.py" in _authenticate_with_backend
  115.     return backend.authenticate(*args, **credentials)

File "/app/decide/base/backends.py" in authenticate
  26.             token = mods.post('authentication', entry_point='/login/', json=data)

File "/app/decide/base/mods.py" in post
  66.     return query(*args, method='post', **kwargs)

File "/app/decide/base/mods.py" in query
  53.         response = q(url, json=json_data, headers=headers)

File "/app/.heroku/python/lib/python3.6/site-packages/requests/api.py" in post
  112.     return request('post', url, data=data, json=json, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/requests/api.py" in request
  58.         return session.request(method=method, url=url, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/requests/sessions.py" in request
  508.         resp = self.send(prep, **send_kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/requests/sessions.py" in send
  618.         r = adapter.send(request, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/requests/adapters.py" in send
  508.             raise ConnectionError(e, request=request)

Exception Type: ConnectionError at /admin/login/
Exception Value: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /authentication/login/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f2e451b9c18>: Failed to establish a new connection: [Errno 111] Connection refused',))
2
Just a reminder to not put your secret key in a public post. I edited it out. You may want to change it now.mechanical_meat
Oops, Thanks for the edit!Loren

2 Answers

0
votes

Django cannot use the default port (8000) on Heroku, but should bind to the one provided in PORT env variable (or DJANGO_PORT).

See https://blog.heroku.com/heroku-django-node

0
votes

I had the local_settings.py file in master and I deployed my app from git, so there was the problem.