Search code examples
djangopython-3.xsession-cookiesdjango-sessionsdjango-2.1

'WSGIRequest' object has no attribute 'sessions' (Django 2.1.2)


I am working on a django web app and I need to use sessions and cookies. I wasn't getting this error before while using sessions and cookies but now It is happening again:

     AttributeError at /dashboard/
    'WSGIRequest' object has no attribute 'sessions'
    Request Method: GET
    Request URL:    http://127.0.0.1:8000/dashboard/
    Django Version: 2.1.2
    Exception Type: AttributeError
    Exception Value:    
    'WSGIRequest' object has no attribute 'sessions
...
def dashboard(request):
    context = {
    }

    request.sessions.set_test_cookie()
    request.sessions["test"] = "This Is A Test"
    return HttpResponse(f'<h1>This Is Where The Dashboard is Going To Be :)</h1><br /><h1>Welcome</h1>')

I already checked my MIDDLEWARE order and made sure that MIDDLEWARE wasn't supposed to be MIDDLEWARE_CLASSES. Here is the code in my settings.py file:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'portalhome.apps.PortalhomeConfig',
    'Users.apps.UsersConfig',
]

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

The wierd thing is is that django is able to set a csrf_token (a cookie) and before this error my sessions were working fine. I also did not change any of the code from when the sessions were working it just stopped working.


Solution

  • You will have session as a property on request. Try using request.session instead of request.sessions.