adel bouakaz
adel bouakaz

Reputation: 341

can't get Primary Key from kwargs

i have this views.py

class AddToCartView(APIView):
    def post(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        print(pk)
        if pk is None:
            return Response({"message": "Invalid request"}, status=HTTP_400_BAD_REQUEST)

        item = get_object_or_404(items, pk=pk)

i am getting None from print(pk), what am i doing wrong?

Upvotes: 1

Views: 299

Answers (1)

Mohamad Malekzahedi
Mohamad Malekzahedi

Reputation: 233

If you have any of these two URLs:

path('..../<int:pk>/...', AddToCartView, ...)
re_path('..../(?pk[0-9]+)/...', AddToCartView, ...)

you can get pk in your view in args of post method.

def post(self, request, pk, **kwargs):
    print(pk)

If you want something else, let us know.

Upvotes: 2

Related Questions