Igl3
Igl3

Reputation: 5108

Authentication User in Django Class Based Views

I'm trying to refactor my django project. Therefore 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))

To 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 issue I'm facing is that I can't get the user details like in the old version by request.user.details as the WSGI-Request does not contain an attribute user. I guess I did something wrong with the decorators but I can't figure it out.

FYI the view is mapped in the urls like this:

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

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

Upvotes: 4

Views: 2118

Answers (1)

Alasdair
Alasdair

Reputation: 309109

According to the Django Rest Framework Authentication Docs, your view should subclass APIView, and set authentication_classes and permission_classes as attributes instead of using the decorators.

from rest_framework.views import APIView

class InactiveVehicleView(APIView):

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

    def get(self, request):
        ...

Upvotes: 3

Related Questions