Home > Software design >  Django Rest Framework - Why am I getting an error when the function isn't even supposed to do a
Django Rest Framework - Why am I getting an error when the function isn't even supposed to do a

Time:01-11

Have this URL:

path("products/product/<int:product>/rating/", ProductRating.as_view()),

and this view to handle the URL:

class ProductRating(APIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = ProductRatingSerializer

    def get(self, request):
        breakpoint()

In the URL the product in int:product is just the id of the product in question. No matter what I put there whether it be int:pk or int:id I get the same error every time:

TypeError: get() got an unexpected keyword argument 'product'

I have tried using generic view RetrieveAPIView and just an APIView and i get the same error. Why am I getting an error and not the breakpoint?

CodePudding user response:

def get(request, request, product):
        breakpoint()

it should work now !

CodePudding user response:

Whenever you deal with a url that have a query parameter(id, pk, slug...) in the path its going to passed to view function as kwarg. so you have either define explicit argument that captures that or u can defined a **kwargs argument in the function.

the implementation:

def get(self, request, product):
    ....

or

def get(self, request, **kwargs):
    product = kwargs.get("product")
    ...

CodePudding user response:

from django.http import JsonResponse


def get(self, request, *args, **kwargs):
   product_id = self.kwargs["product"]
   breakpoint()
   return JsonResponse(data={"status": "200, Yay it works"})

CodePudding user response:

code like below dear

class ProductRating(APIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = ProductRatingSerializer

    def get(request, request, format=None):
        breakpoint()
  • Related