django-rest-framework中的django.contrib.auth.decorators login_required

3

我正在实现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'

以下是 views.py,其中用户使用django.contrib.auth的用户登录功能进行登录。
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_required,我尝试将@login_required更改为@method_decorator(login_required)。未发生错误,但触发了GET另一个方法"GET /accounts/login/?next=/questions/ HTTP/1.1" 200 17

有人能解释如何解决此问题或正确使用@login_required吗?

1个回答

1
当您使用DRF时,您应该为您的 APIView 设置权限类。重构您的代码,像这样,它应该能够正常工作:
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated


class QuestionListView(APIView):
    permission_classes = [IsAuthenticated, ]
    authentication_classes = [SessionAuthentication, ]

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

我收到了“Forbidden: /questions/”的错误。 - ceciliamv
那么您可能没有登录。请尝试使用管理员面板(例如)/admin/登录。 - nima

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接