django rest框架需要django.contrib.auth.decorators登录\u

django rest框架需要django.contrib.auth.decorators登录\u,django,reactjs,authentication,django-rest-framework,Django,Reactjs,Authentication,Django Rest Framework,我正在我的web应用程序中实现登录功能,但发生了此错误 File ".../venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 20, in _wrapped_view if test_func(request.user): AttributeError: 'QuestionListView' object has no attribute 'user' 下面是使用django.contri

我正在我的web应用程序中实现登录功能,但发生了此错误

File ".../venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 20, in _wrapped_view
    if test_func(request.user):
AttributeError: 'QuestionListView' object has no attribute 'user'
下面是使用django.contrib.auth的用户登录功能登录的
views.py

class QuestionListView(APIView):
    @login_required
    def get(self, request, format=None):
        return Response({'message': 'try', 'status': 1})

class UserLoginView(APIView):
    def post(self, request, format=None):
        data = request.data
        user = authenticate(
            username=data['username'], password=data['password'])

        if user is not None:
            login(request, user)
            return Response({'message': 'Login successful', 'status': 1})
        else:
            return Response({'message': 'Wrong password', 'status': 0})
url.py

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^accounts/login/$', views.UserLoginView.as_view()),
    url(r'^questions/$', views.QuestionListView.as_view()),
]
因为我使用的是React JS,所以我使用
window.location.href='/'重定向页面。(我也不确定这是否是重定向页面的适当方式)

关于,我尝试将
@login\u required
更改为
@method\u decorator(login\u required)
。没有发生错误,但它触发了获取另一个方法
“GET/accounts/login/?next=/questions/HTTP/1.1”200 17


有人能解释一下如何解决这个问题或正确使用@login\u required吗?

当您使用DRF时,您应该为您的
APIView设置权限类。像这样重构代码,它应该可以正常工作:

来自rest\u framework.authentication导入会话身份验证
从rest_framework.permissions导入已验证
类问题列表视图(APIView):
权限\u类=[IsAuthenticated,]
身份验证\u类=[SessionAuthentication,]
def get(自我、请求、格式=无):
返回响应({'message':'try','status':1})

我收到了
禁止的:/questions/
相反,您可能没有登录。尝试使用您的管理面板登录(例如)
/admin/