sandeep
sandeep

Reputation: 711

DRF: data is not passing to kwargs in patch method

I am creating a update comment view for my app. This is my code:

serializer.py

class CommentSerializer(serializers.ModelSerializer):

    class Meta:
        model = FitnessRecord
        fields = ('comment', 'id')

views.py

class AddCommentView(APIView):
    permission_classes = [IsAuthenticated]

    def patch(self, request, *args, **kwargs):
        print(kwargs) # this is printing {}
        instance = get_object_or_404(FitnessRecord, pk=kwargs.get('id')) # error line
        print(22222) # not printing
        serializer = CommentSerializer(instance, data=request.data, partial=True)

        if serializer.is_valid():

            serializer.save()

            return Response(CommentSerializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I am using postman to send data. this is the error:

{
    "detail": "Not found."
}

This may be because kwargs is blank.

I am passing this data.

{
    "comment": "gotham#bw9",
    "id": 14
}

This is DRF setting if required.

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DATE_INPUT_FORMATS': ['%d-%m-%Y'],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'TEST_REQUEST_DEFAULT_FORMAT': 'json'
}

Upvotes: 0

Views: 901

Answers (2)

uedemir
uedemir

Reputation: 1714

You can get sent payload with request.data;

def patch(self, request, *args, **kwargs):
    print(request.data) # this will print {"comment": "gotham#bw9", "id": 14}
    ...

Upvotes: 1

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11695

you should pass the kwarg id in the url. See example below

URL:

http://localhost:8000/comment/14/

Request method: PATCH

Data:

{
    "comment": "gotham#bw9",
}

Upvotes: 1

Related Questions