Reputation: 711
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
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
Reputation: 11695
you should pass the kwarg id
in the url. See example below
http://localhost:8000/comment/14/
{
"comment": "gotham#bw9",
}
Upvotes: 1