Authenticating user in Django based classes

I am trying to refactor a django project. So I want to refactor from:

    @api_view([GET, POST])
    @permission_classes((IsAuthenticated, VehiclePermissions, ))
    def inactive_vehicle_view(request):

        if request.method == "GET":
            con = CBaseUtil.get_prod_instance()
            vehicle_bo = VehicleBO()
            dongle_dao = OBDDongleDAO(con)

            since_days = int(request.GET.get("since", 28))

            vehicles = vehicle_bo.find_vehicles_by_user_context(request.user.details)

            return Response(vehicles, status=status_code, headers=get_headers(request))

      

For a class based view like this:

class InactiveVehicleView(View):

    @authentication_classes((BasicAuthentication, WebsiteAuthentication))
    @permission_classes((IsAuthenticated, VehiclePermissions, ))
    def dispatch(self, *args, **kwargs):
        return super(InactiveVehicleView, self).dispatch(*args, **kwargs)

    def get(self, request):
        con = CBaseUtil.get_prod_instance()
        vehicle_bo = VehicleBO()
        dongle_dao = OBDDongleDAO(con)

        since_days = int(request.GET.get("since", 28))

        vehicles = vehicle_bo.find_vehicles_by_user_context(request.user.details)

        return Response(vehicles, status=status_code, headers=get_headers(request))

      

The problem I'm running into is that I can't get the user information like in the old version, request.user.details, since the WSGI-Request doesn't contain the user attribute. I think I did something wrong with decorators, but I can't figure it out.

FYI view is rendered in URLs like this:

url(r'^vehicles/inactive/?$', InactiveVehicleView.as_view())

      

Does anyone have an idea what I did wrong with authentication and / or decorators?

+3


source to share


1 answer


According to the Django Rest Framework Authentication Docs, your view should be subclassed APIView

and set authentication_classes

and permission_classes

as attributes instead of using decorators.



from rest_framework.views import APIView

class InactiveVehicleView(APIView):

    authentication_classes = (BasicAuthentication, WebsiteAuthentication)
    permission_classes = (IsAuthenticated, VehiclePermissions)

    def get(self, request):
        ...

      

+3


source







All Articles