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

Question:

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:serverwww>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:serverenvlibsite-packagesdjangocorehandlersexception.py", line 39, in inner
    response = get_response(request)
  File "C:serverenvlibsite-packagesdjangoutilsdeprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "C:serverenvlibsite-packagesdjangocorehandlersexception.py", line 41, in inner
    response = response_for_exception(request, exc)
  File "C:serverenvlibsite-packagesdjangocorehandlersexception.py", line 86, in response_for_exception
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
  File "C:serverenvlibsite-packagesdjangocorehandlersexception.py", line 124, in handle_uncaught_exception
    extra={'status_code': 500, 'request': request},
  File "c:pythonLiblogging__init__.py", line 1308, in error
    self._log(ERROR, msg, args, **kwargs)
  File "c:pythonLiblogging__init__.py", line 1415, in _log
    self.handle(record)
  File "c:pythonLiblogging__init__.py", line 1425, in handle
    self.callHandlers(record)
  File "c:pythonLiblogging__init__.py", line 1487, in callHandlers
    hdlr.handle(record)
  File "c:pythonLiblogging__init__.py", line 855, in handle
    self.emit(record)
  File "C:serverenvlibsite-packagesdjangoutilslog.py", line 121, in emit
    self.send_mail(subject, message, fail_silently=True, html_message=html_message)
  File "C:serverenvlibsite-packagesdjangoutilslog.py", line 124, in send_mail
    mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)
  File "C:serverenvlibsite-packagesdjangocoremail__init__.py", line 103, in mail_admins
    mail.send(fail_silently=fail_silently)
  File "C:serverenvlibsite-packagesdjangocoremailmessage.py", line 342, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:serverenvlibsite-packagesdjangocoremailbackendssmtp.py", line 100, in send_messages
    new_conn_created = self.open()
  File "C:serverenvlibsite-packagesdjangocoremailbackendssmtp.py", line 58, in open
    self.connection = connection_class(self.host, self.port, **connection_params)
  File "c:pythonLibsmtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "c:pythonLibsmtplib.py", line 335, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "c:pythonLibsmtplib.py", line 306, in _get_socket
    self.source_address)
  File "c:pythonLibsocket.py", line 711, in create_connection
    raise err
  File "c:pythonLibsocket.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:pythonLibwsgirefhandlers.py", line 137, in run
    self.result = application(self.environ, self.start_response)
  File "C:serverenvlibsite-packagesdjangocorehandlerswsgi.py", line 170, in __call__
    response = self.get_response(request)
  File "C:serverenvlibsite-packagesdjangocorehandlersbase.py", line 124, in get_response
    response = self._middleware_chain(request)
  File "C:serverenvlibsite-packagesdjangocorehandlersexception.py", line 41, in inner
    response = response_for_exception(request, exc)
  File "C:serverenvlibsite-packagesdjangocorehandlersexception.py", line 86, in response_for_exception
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
  File "C:serverenvlibsite-packagesdjangocorehandlersexception.py", line 124, in handle_uncaught_exception
    extra={'status_code': 500, 'request': request},
  File "c:pythonLiblogging__init__.py", line 1308, in error
    self._log(ERROR, msg, args, **kwargs)
  File "c:pythonLiblogging__init__.py", line 1415, in _log
    self.handle(record)
  File "c:pythonLiblogging__init__.py", line 1425, in handle
    self.callHandlers(record)
  File "c:pythonLiblogging__init__.py", line 1487, in callHandlers
    hdlr.handle(record)
  File "c:pythonLiblogging__init__.py", line 855, in handle
    self.emit(record)
  File "C:serverenvlibsite-packagesdjangoutilslog.py", line 121, in emit
    self.send_mail(subject, message, fail_silently=True, html_message=html_message)
  File "C:serverenvlibsite-packagesdjangoutilslog.py", line 124, in send_mail
    mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)
  File "C:serverenvlibsite-packagesdjangocoremail__init__.py", line 103, in mail_admins
    mail.send(fail_silently=fail_silently)
  File "C:serverenvlibsite-packagesdjangocoremailmessage.py", line 342, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:serverenvlibsite-packagesdjangocoremailbackendssmtp.py", line 100, in send_messages
    new_conn_created = self.open()
  File "C:serverenvlibsite-packagesdjangocoremailbackendssmtp.py", line 58, in open
    self.connection = connection_class(self.host, self.port, **connection_params)
  File "c:pythonLibsmtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "c:pythonLibsmtplib.py", line 335, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "c:pythonLibsmtplib.py", line 306, in _get_socket
    self.source_address)
  File "c:pythonLibsocket.py", line 711, in create_connection
    raise err
  File "c:pythonLibsocket.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.

Asked By: Jacob Jewett

||

Answers:

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.

Answered By: Jacob Jewett

reinstall django by python django –upgrade

Answered By: Bbxxest Olumese

in my case I forgot to setup the email backend and the authentication. I solved it by adding this to the setting file.

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",

    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",
)
Answered By: Bismark Obeng

In my case, the error occurred when I was using django-allauth without configuring Email Backends Setting. Since there was no email backend defined, it used default SMTP backend which was trying to send an email to the user. though there is no SMTP setup and thus, the default host failed to connect, and therefore, we got this error. The answer above this one, where the person is setting the email backend did work for me. Though the question is generalized, I faced the error due to the allauth package and not Django or the server-related problem itself.
You can set it to console or according to smtp.

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",

    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",
)
Answered By: Karan Mittal

this type of error occur no setting is set in setting copy below and paste and check

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Answered By: deepak Saini

Yes but the easier way is to put this into your local settings:

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

Then all emails will be printed in your console.

Answered By: Tsrek Alu