Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Django 2.0 : 'WSGIRequest' object has no attribute 'session'

Tags:

django

I upgraded my Django version from 1.11.5 to 2.0 and I'm trying to solve different deprecated element.

However, even if my CSS/bootstrap style sheet doesn't work, I don't overcome to log into my Django software. I have this issue :

'WSGIRequest' object has no attribute 'session'

This is the entire Traceback :

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/Authentification/Login/

Django Version: 2.0
Python Version: 3.6.2
Installed Applications:
['Institution',
 'django.conf.urls',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'bootstrapform',
 'django_countries',
 'chartit',
 'Configurations',
 'Home',
 'Authentication',
 'Identity',
 'rest_framework',
 'Fiscal',
 'bootstrap4']
Installed Middleware:
[]



Traceback:

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/Users/valentinjungbluth/Desktop/Django/DatasystemsCORE/DatasystemsCore/DatasystemsCORE/Authentication/views.py" in Login
  26.                 login(request, user)  

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/contrib/auth/__init__.py" in login
  130.     if SESSION_KEY in request.session:

Exception Type: AttributeError at /Authentification/Login/
Exception Value: 'WSGIRequest' object has no attribute 'session'

In my Authentification app :

# views.py file
#-*- coding: utf-8 -*-

from django.contrib.auth import authenticate, login, logout
from .forms import ConnexionForm
from django.shortcuts import render, reverse, get_object_or_404, redirect
from django.http import HttpResponseRedirect, HttpResponse
from .models import LoggedUsers

from API_GED import Logger

import datetime
from django.views.decorators.csrf import csrf_exempt,csrf_protect


@csrf_exempt
def Login(request):
    error = False

    if request.method == "POST":
        form = ConnexionForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            user = authenticate(username=username, password=password)  # Nous vérifions si les données sont correctes
            if user:  # Si l'objet renvoyé n'est pas None
                login(request, user)  

                response = redirect('Homepage')

                return response

            else: # sinon une erreur sera affichée
                error = True

    else:
        form = ConnexionForm()

    return render(request, 'Authentication_Homepage.html', locals())


def Logout(request):

    logout(request)

    return redirect(reverse('Choice'))


def ConnectedUsers(request) :

    logged_users = LoggedUsers.objects.all()
    print (logged_users)

    logged_users_number = LoggedUsers.objects.all().count()

    context = {
        "logged_users":logged_users,
        "logged_users_number":logged_users_number,
    }

    return render(request, "Authentication_LoggedUsers.html", context)

An my models.py file :

from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_in, user_logged_out 

# class UserProfile(models.Model):
#     user   = models.OneToOneField(User)
#     avatar = models.ImageField(upload_to='/images/')

class LoggedUsers(models.Model):
    user = models.ForeignKey(User, primary_key=True, on_delete=models.CASCADE)

    def __str__(self):
        return '{}{}{}'.format(self.user.first_name + " ",  self.user.last_name  + " (", self.user.username + ")")

def login_user(sender, request, user, **kwargs):
        LoggedUsers(user=user).save()

def logout_user(sender, request, user, **kwargs):
        try:
            u = LoggedUsers.objects.get(user=user)
            u.delete()
        except LoggedUsers.DoesNotExist:
            pass

user_logged_in.connect(login_user)
user_logged_out.connect(logout_user)

In my settings.py file, I have MIDDLEWARE_CLASSES :

MIDDLEWARE_CLASSES = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.gzip.GZipMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'DatasystemsCORE.middleware.OnlineNowMiddleware',
]

Any idea ?

EDIT :

I wrote MIDDLEWARE like this :

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

It seems to work !

like image 849
Essex Avatar asked Dec 05 '17 09:12

Essex


2 Answers

So the MIDDLEWARE_CLASSES changed to MIDDLEWARE https://docs.djangoproject.com/en/2.0/topics/http/middleware/#activating-middleware

like image 92
Sandeep Balagopal Avatar answered Nov 17 '22 15:11

Sandeep Balagopal


MIDDLEWARE_CLASSES has been deprecated since Django 1.10 and was removed completely in version 2.0. That means you have no middleware at all.

You should use the MIDDLEWARE setting instead; note, that uses new-style middleware, you might need to upgrade your custom middleware class.

like image 8
Daniel Roseman Avatar answered Nov 17 '22 15:11

Daniel Roseman