WinError 10061 No connection could be made because the target machine actively refused it - Django Python Error when Sending Email

I’m just learning Django and wasn’t able to figure this out.

I’m trying to make my Django App send emails. But keep encountering this error on Submitting . Error Image

I’ve turned the Allow less secure apps option ON in Gmail Settings, & have tried adding

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

But doing that just shows the email in the console rather than actually sending it, which doesn’t serve the purpose

Settings.py




from pathlib import Path
import os
from django.forms import EmailField
import django_heroku
from django.contrib import messages
from dotenv import load_dotenv
load_dotenv()

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


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-*akbxcj*md2z0&#vai@lw816t6p#te!fdo^#4j194^x7r7p-zo'

# 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',
    'expenses'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    #'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'expenseswebsite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'expenseswebsite.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ.get('DB_NAME'),
        'USER': os.environ.get('DB_USER'),
        'PASSWORD': os.environ.get('DB_USER_PASSWORD'),
        'HOST': os.environ.get('DB_HOST'),
        
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.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',
    },
]


CSRF_COOKIE_SECURE = False


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


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

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



django_heroku.settings(locals()) #to create local heroku settings 

MESSAGE_TAGS = {

    messages.ERROR : 'danger' #to change the error in django to danger in bootstrap

}

#Emails



EMAIL_HOST: os.environ.get('EMAIL_HOST')
EMAIL_HOST_USER: os.environ.get('EMAIL_HOST_USER')
EMAIL_USE_TLS: True
DEFAULT_FROM_EMAIL: os.environ.get('EMAIL_HOST_USER')
EMAIL_PORT: 587
EMAIL_HOST_PASSWORD: os.environ.get('EMAIL_HOST_PASSWORD')













# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Code in Views.py that deals with Email and Registration

class RegistrationView(View):
    def get(self, request):
        return render(request, 'authentication/register.html')

    def post(self, request):

        #TO REGISTER A USER
            #GET USER DATA
            #VALIDATE USER
            #CREATE USER ACCNT

       
        username = request.POST['username']
        email = request.POST['email']
        password = request.POST['password']   

        #TO KEEP THE VALUE EVEN AFTER MESSAGE


        context = {
            'fieldValues': request.POST
        }   

        if not User.objects.filter(username = username).exists():
            if not User.objects.filter(email = email).exists():
                if len(password) < 6:
                    messages.error(request, 'Password too Short')
                    return render(request, 'authentication/register.html', context)

                if len(password) > 36:
                    messages.error(request, 'Password too Long')
                    return render(request, 'authentication/register.html', context)

                user = User.objects.create_user(username = username, email = email)
                user.set_password(password)
                user.is_active = False
                user.save()
                email_subject = 'Activate your Account'
                email_body = 'Test Link Register Body'
                email = EmailMessage(
                    email_subject,
                    email_body,
                    'noreply@test.com',
                    [email],
                    
                )
                email.send(fail_silently=False)
                messages.success(request, 'Account Created Succesfully')
                return render(request, 'authentication/register.html')




        return render(request, 'authentication/register.html')

The .env looks something like this

export DB_NAME =test                                                                                   
export DB_USER =test                                                                                  
export DB_USER_PASSWORD =test                                                                                                                                                                
export EMAIL_PASSWORD =test                                                                                   
export EMAIL_HOST_USER =test@gmail.com                                                                                   
export DEFAULT_FROM_EMAIL =test@gmail.com                                                                                   
export EMAIL_HOST =smtp.gmail.com

What could be going wrong?
OS → Windows 11