Django REST: AttributeError: 'WSGIRequest' object has no attribute 'session'

Django REST: AttributeError: 'WSGIRequest' object has no attribute 'session'

我已经为我的 Django 应用程序创建了一个登录 API视图。我不断收到错误,AttributeError:'WSGIRequest' 对象没有属性 'session'。我看过其他帖子,有人提到重新排序中间件,首先放置 sessionMIddleware,但这是行不通的。这是 API 的设置。错误发生在登录(请求,用户)时。

from django.contrib.auth import authenticate, login
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import LoginSerializer
from rest_framework.permissions import AllowAny


class Login(APIView):
    permission_classes = (AllowAny, )
    authentication_classes = ()
    serializer = LoginSerializer

    def post(self, request, format=None):
    login_form = self.serializer(data=request.data)
    data = dict()
    if login_form.is_valid():
        username = login_form.data['username']
        password = login_form.data['password']
        user = authenticate(username=username, password=password)

        if user is not None:
            print(request.data)
            login(request, user)
            data['data'] = 'OK'
            return Response(data=data, status=200)
        else:
            data['error'] = 'Invalid login information provided'
            return Response(data=data, status=401)
    else:
        data['invalid'] = 'Bad Request, form is invalid'
        return Response(data=data, status=400)

好的,我在 settings.py 中将我的中间件定义为 MIDDLEWARE,而不是 MIDDLEWARE_CLASSES。 Pycharm 在我设置新项目时为我生成了它。我相信 Django 1.10 使用 MIDDLEWARE 而我使用的是 1.9。