Rahul Sharma
Rahul Sharma

Reputation: 2495

Get pk from URL in django rest framework

I am trying to access the pk from URL but getting the following error:

get() got multiple values for argument 'pk'

URL:

            path('grn-barcodes/<int:pk>/', GrnBarcodes.as_view()),

Views.py

class GrnBarcodes(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self,pk):
        pk = self.kwargs['pk']
        print("pk is", pk)
        .
        .
        .
        return Response("done")

How do I get it in the Function?

Upvotes: 1

Views: 4510

Answers (3)

hari19
hari19

Reputation: 137

Try the url in this format,

path(r'grn-barcodes/(?P<pk>\d+)', GrnBarcodes.as_view())

Also, the view should have request parameter as HuLu ViCa stated

class GrnBarcodes(APIView):
permission_classes = (permissions.IsAuthenticated,)

def get(self, request, pk):
    pk = self.kwargs['pk']
    print("pk is", pk)
    .
    .
    .
    return Response("done")

Upvotes: 0

Arjun Shahi
Arjun Shahi

Reputation: 7330

You should define your get method like this.

def get(self, request, *args, **kwargs):
       pk = self.kwargs['pk']

Upvotes: 2

HuLu ViCa
HuLu ViCa

Reputation: 5452

You are missing request parameter:

class GrnBarcodes(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, pk):
        pk = self.kwargs['pk']
        print("pk is", pk)
        .
        .
        .
        return Response("done")

Upvotes: 0

Related Questions