Django Python - No connection could be made because the target machine actively refused it

Jacob Jewett picture Jacob Jewett · Dec 29, 2016 · Viewed 11.2k times · Source

I have a Django python server in a virtual environment at the root of my hard drive. In the command line, when I activate the env and run python manage.py 192.168.0.47:80 it starts the server normal (no migration notice or anything), but when I load the page from the browser (using instancegaming.net locally, which is in my servers host file and has worked fine in the past locally and remotely) it loads and loads forever, and when I go to the Django server window and do Ctrl+C it updates the console and gives me the following error. Keep in mind that this env is a fresh install, with no other site packages other than Django. I've had successfully ran servers before on the same server (Windows 10 64-bit) and with the same router config.

I've looked at other posts like this (Python Django-Helpdesk Error: No connection could be made because the target machine actively refused it) and a handful of others, but none of these seem to solve the problem.

Console Window:

(env) C:\server\www>python manage.py runserver 192.168.0.47:80
Performing system checks...

System check identified no issues (0 silenced).
December 28, 2016 - 19:07:06
Django version 1.10.4, using settings 'www.settings'
Starting development server at http://192.168.0.47:80/
Quit the server with CTRL-BREAK.
 Traceback (most recent call last):
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\server\env\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = response_for_exception(request, exc)
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 86, in response_for_exception
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 124, in handle_uncaught_exception
    extra={'status_code': 500, 'request': request},
  File "c:\python\Lib\logging\__init__.py", line 1308, in error
    self._log(ERROR, msg, args, **kwargs)
  File "c:\python\Lib\logging\__init__.py", line 1415, in _log
    self.handle(record)
  File "c:\python\Lib\logging\__init__.py", line 1425, in handle
    self.callHandlers(record)
  File "c:\python\Lib\logging\__init__.py", line 1487, in callHandlers
    hdlr.handle(record)
  File "c:\python\Lib\logging\__init__.py", line 855, in handle
    self.emit(record)
  File "C:\server\env\lib\site-packages\django\utils\log.py", line 121, in emit
    self.send_mail(subject, message, fail_silently=True, html_message=html_message)
  File "C:\server\env\lib\site-packages\django\utils\log.py", line 124, in send_mail
    mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)
  File "C:\server\env\lib\site-packages\django\core\mail\__init__.py", line 103, in mail_admins
    mail.send(fail_silently=fail_silently)
  File "C:\server\env\lib\site-packages\django\core\mail\message.py", line 342, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:\server\env\lib\site-packages\django\core\mail\backends\smtp.py", line 100, in send_messages
    new_conn_created = self.open()
  File "C:\server\env\lib\site-packages\django\core\mail\backends\smtp.py", line 58, in open
    self.connection = connection_class(self.host, self.port, **connection_params)
  File "c:\python\Lib\smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "c:\python\Lib\smtplib.py", line 335, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "c:\python\Lib\smtplib.py", line 306, in _get_socket
    self.source_address)
  File "c:\python\Lib\socket.py", line 711, in create_connection
    raise err
  File "c:\python\Lib\socket.py", line 702, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
  File "c:\python\Lib\wsgiref\handlers.py", line 137, in run
    self.result = application(self.environ, self.start_response)
  File "C:\server\env\lib\site-packages\django\core\handlers\wsgi.py", line 170, in __call__
    response = self.get_response(request)
  File "C:\server\env\lib\site-packages\django\core\handlers\base.py", line 124, in get_response
    response = self._middleware_chain(request)
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = response_for_exception(request, exc)
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 86, in response_for_exception
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
  File "C:\server\env\lib\site-packages\django\core\handlers\exception.py", line 124, in handle_uncaught_exception
    extra={'status_code': 500, 'request': request},
  File "c:\python\Lib\logging\__init__.py", line 1308, in error
    self._log(ERROR, msg, args, **kwargs)
  File "c:\python\Lib\logging\__init__.py", line 1415, in _log
    self.handle(record)
  File "c:\python\Lib\logging\__init__.py", line 1425, in handle
    self.callHandlers(record)
  File "c:\python\Lib\logging\__init__.py", line 1487, in callHandlers
    hdlr.handle(record)
  File "c:\python\Lib\logging\__init__.py", line 855, in handle
    self.emit(record)
  File "C:\server\env\lib\site-packages\django\utils\log.py", line 121, in emit
    self.send_mail(subject, message, fail_silently=True, html_message=html_message)
  File "C:\server\env\lib\site-packages\django\utils\log.py", line 124, in send_mail
    mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)
  File "C:\server\env\lib\site-packages\django\core\mail\__init__.py", line 103, in mail_admins
    mail.send(fail_silently=fail_silently)
  File "C:\server\env\lib\site-packages\django\core\mail\message.py", line 342, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:\server\env\lib\site-packages\django\core\mail\backends\smtp.py", line 100, in send_messages
    new_conn_created = self.open()
  File "C:\server\env\lib\site-packages\django\core\mail\backends\smtp.py", line 58, in open
    self.connection = connection_class(self.host, self.port, **connection_params)
  File "c:\python\Lib\smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "c:\python\Lib\smtplib.py", line 335, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "c:\python\Lib\smtplib.py", line 306, in _get_socket
    self.source_address)
  File "c:\python\Lib\socket.py", line 711, in create_connection
    raise err
  File "c:\python\Lib\socket.py", line 702, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
[28/Dec/2016 19:08:15] "GET / HTTP/1.1" 500 59

My settings.py:

import os

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

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

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

ALLOWED_HOSTS = [
    '.instancegaming.net',
]


# Application definition

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

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 = 'www.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 = 'www.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'MST'

USE_I18N = True

USE_L10N = True

USE_TZ = True

ADMINS = (('Jacob J','[email protected]'))

MANAGERS = ADMINS

STATICFILES_DIRS = (
    'C:/server/web/static/',
)
STATIC_ROOT = 'C:/server/Apache2/htdocs/cdn/main/'
STATIC_URL = 'http://instancegaming.net:81/cdn/main/'

The console error loops on forever anytime I update the console log (for instance, pressing enter or doing Ctrl+C.)

When I go to canyouseeme.org, on port 80 when the server is running, it says it can see the service. Additionally, I have a clean Apache 2 server running on port :81 that works completely fine both locally and remotely. Additionally, when I run a python script to simply check port 80, it gives the same (simplified) error as above.

Port checker script:

    import socket
s = socket.socket()
address = '127.0.0.1' # or 192.168.0.47
port = 80  # port number is a number, not string
try:
    s.connect((address, port)) 
    # originally, it was 
    # except Exception, e: 
    # but this syntax is not supported anymore. 
except Exception as e: 
    print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
    s.close()

Which returns the following,

[WinError 10061] No connection could be made because the target machine actively refused it

Lastly, I've tried to make a clean env with Django hoping it would change something, but it to, a fresh, out of the box copy gave the exact same error.

Answer

Jacob Jewett picture Jacob Jewett · Jan 5, 2017

I ended up fixing this problem quite easily. I originally though it had something to do with the socket 80, but after doing some deep thinking, I turned DEBUG = True and found out that I had a missing template for the home dir, and links to unknown pages. For anyone who has this error, please try turning on DEBUG if you can.