18

Similar to this question 'WSGIRequest' object has no attribute 'session'

But my MIDDLEWARE classes are in the correct order.

INSTALLED_APPS = [
    'django.contrib.sessions',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'membership',
    'treebeard',
    'haystack',
    'reversion',
]

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

I am redirecting to login

url(r'^$',  RedirectView.as_view(url='login/')),
url(r'^login/$', 'membership.views.loginView', name='login'),

and then

def loginView(request):
    a = request.session

Throws the error

Community
  • 1
  • 1
Shawn Anderson
  • 323
  • 1
  • 2
  • 8

4 Answers4

26

MIDDLEWARE is a new setting in 1.10 that will replace the old MIDDLEWARE_CLASSES.

Since you're currently on 1.9, Django doesn't recognize the MIDDLEWARE setting. You should use the MIDDLEWARE_CLASSES setting instead:

MIDDLEWARE_CLASSES = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
knbk
  • 52,111
  • 9
  • 124
  • 122
  • 5
    Django 2.0 uses `MIDDLEWARE` now instead of `MIDDLEWARE_CLASSES`, as pointed out by @Slipstream and [in this thread](https://stackoverflow.com/a/47650447/1218179) – mateuszb Mar 25 '18 at 23:01
18

Django 2.0

You can try this in your settings.py, MIDDLEWARE_CLASSES = [....]:

  • Change MIDDLEWARE_CLASSES=[...] to MIDDLEWARE=[...]

  • Remove SessionAuthenticationMiddleware from the MIDDLEWARE=[...] list.

The MIDDLEWARE_CLASSES setting is deprecated in Django 1.10, and removed in Django 2.0.

The SessionAuthenticationMiddleware class is removed. It provided no functionality since session authentication is unconditionally enabled in Django 1.10.

Community
  • 1
  • 1
Slipstream
  • 13,455
  • 3
  • 59
  • 45
5

This error can also be thrown when you have a typo. i.e.

request.sesion ... 

instead of

request.session ... 
Michel K
  • 641
  • 1
  • 6
  • 18
2

Check the order of the middleware, if you are trying to access it on some middlewares which are listed above the session middleware, you will get this error.

Thomas John
  • 2,138
  • 2
  • 22
  • 38