Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django.contrib.auth.decorators login_required with django-rest-framework

I am implementing login functions in my web app, but this error occurred.

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'

Below is views.py, where the user is logged in using django.contrib.auth's user login function.

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()),
]

Since I am using React JS, I redirect the page using window.location.href = '/'; after the login button is clicked. (I am also not sure whether this is an appropriate way to redirect the page)

With reference to class has no attributed user, I tried changing @login_required to @method_decorator(login_required). No error occurred, but instead it triggered GET another method "GET /accounts/login/?next=/questions/ HTTP/1.1" 200 17

Can anyone explain how to fix this problem or to properly use @login_required?

like image 399
ceciliamv Avatar asked Nov 19 '25 12:11

ceciliamv


1 Answers

When you are using DRF, you should set permission classes for your APIView. Refactor your code like this, and it should work properly:

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})
like image 193
nima Avatar answered Nov 22 '25 01:11

nima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!