How to fix Session matching query does not exist?

I made a raw django website to prevent multiple sessions by a user. It worked fine locally but it started throwing errors when I uploaded it to pythonanywhere. This happened after I logged into the site. If you want to log into the site use: E-mail: career Pwd: Qazpl,@123 Here is the error, I get:

Environment:


Request Method: GET
Request URL: https://careerabacusgallery.pythonanywhere.com/

Django Version: 4.0.1
Python Version: 3.9.5
Installed Applications:
['onlinetest.apps.OnlinetestConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed 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',
 'onlinetest.middleware.OneSessionPerUserMiddleware']



Traceback (most recent call last):
  File "/home/careerabacusgallery/.virtualenvs/test/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/careerabacusgallery/statelevel/onlinetest/middleware.py", line 19, in __call__
    Session.objects.get(session_key=stored_session_key).delete()
  File "/home/careerabacusgallery/.virtualenvs/test/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/careerabacusgallery/.virtualenvs/test/lib/python3.9/site-packages/django/db/models/query.py", line 439, in get
    raise self.model.DoesNotExist(

Exception Type: DoesNotExist at /
Exception Value: Session matching query does not exist.

My settings.py:

"""
Django settings for statelevel project.

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

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

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

from pathlib import Path
import os

# 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 = ''

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

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'onlinetest.apps.OnlinetestConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

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',
    'onlinetest.middleware.OneSessionPerUserMiddleware'
]

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


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


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


# 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/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''

My models.py:

from django.db import models
from django.conf import settings

User = settings.AUTH_USER_MODEL

# Model to store the list of logged in users
class LoggedInUser(models.Model):
    user = models.OneToOneField(User, related_name='logged_in_user', on_delete=models.DO_NOTHING)
    # Session keys are 32 characters long
    session_key = models.CharField(max_length=32, null=True, blank=True)

    def __str__(self):
        return self.user.username

class User_log(models.Model):
    E_Mail = models.CharField(max_length=122)
    IP = models.CharField(max_length=122)
    def __str__(self):
        return str(self.E_Mail)

My urls.py:

from django.urls import path
from onlinetest import views

urlpatterns = [
    path("", views.home, name='Home Page'),
    path("lgi", views.loggedin, name='Log In Page'),
    path("lgu", views.logoutuser, name='Log Out Page'),
]

My apps.py:

from django.apps import AppConfig

class OnlinetestConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'onlinetest'
    # This function is the only new thing in this file
    # it just imports the signal file when the app is ready
    def ready(self):
        import onlinetest.signals

My middleware.py:

#Session model stores the session data
from django.contrib.sessions.models import Session

class OneSessionPerUserMiddleware:
    # Called only once when the web server starts
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        if request.user.is_authenticated:
            stored_session_key = request.user.logged_in_user.session_key

            # if there is a stored_session_key  in our database and it is
            # different from the current session, delete the stored_session_key
            # session_key with from the Session table
            if stored_session_key and stored_session_key != request.session.session_key:
                Session.objects.get(session_key=stored_session_key).delete()

            request.user.logged_in_user.session_key = request.session.session_key
            request.user.logged_in_user.save()

        response = self.get_response(request)

        # This is where you add any extra code to be executed for each request/response after
        # the view is called.
        # For this tutorial, we're not adding any code so we just return the response

        return response

My signals.py:

# Signals that fires when a user logs in and logs out

from django.contrib.auth import user_logged_in, user_logged_out
from django.dispatch import receiver
from onlinetest.models import LoggedInUser

@receiver(user_logged_in)
def on_user_logged_in(sender, request, **kwargs):
    LoggedInUser.objects.get_or_create(user=kwargs.get('user'))


@receiver(user_logged_out)
def on_user_logged_out(sender, **kwargs):
    LoggedInUser.objects.filter(user=kwargs.get('user')).delete()

My views.py:

from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
# from datetime import datetime
# import pytz
# from onlinetest.models import ContactMessage
# from django.core.mail import EmailMessage
from django.conf import settings
from onlinetest.models import User_log

def home(request):
    if request.user.is_anonymous:
        pass
    else:
        return redirect('/lgi')

    if request.method=='POST':
        username = request.POST.get('email')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)

            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]
            else:
                ip = request.META.get('REMOTE_ADDR')
            
            userlog= User_log(E_Mail=username, IP=ip)
            userlog.save()

            return redirect('/lgi')
        else:
            return render(request, 'login.html')
    # if request.method=='POST':
    #     Name = request.POST.get('name')
    #     Message = request.POST.get('message')
    #     E_Mail = request.POST.get('email')
    #     IST = pytz.timezone('Asia/Kolkata')
    #     datetime_ist = datetime.now(IST)
    #     current_time = datetime_ist.strftime('%H:%M:%S')
    #     Date= datetime_ist.strftime('%d-%m-%Y')
    #     Time=current_time
    #     contactmessage= ContactMessage(Name=Name, Message = Message, E_Mail=E_Mail, Date= datetime_ist.strftime('%Y-%m-%d'), Time=current_time)
    #     contactmessage.save()
    #     body = "Name: "+Name+"\nE-Mail: "+E_Mail+"\nMessage: "+Message+"\nDate: "+Date+"\nTime: "+Time
    #     email = EmailMessage('New Message - Career Abacus', body, settings.EMAIL_HOST_USER, ['nakulsharma1105@gmail.com', 'careermakers611@hotmail.com'])
    #     email.fail_silently = True
    #     email.send()
    return render(request, 'login.html')

def logoutuser(request):
    logout(request)
    return redirect('/')

def loggedin(request):
    if request.user.is_anonymous:
        return redirect('/')
    else:
        pass
    
    return render(request, 'loggedin.html')

Here is my website url: https://careerabacusgallery.pythonanywhere.com/

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum