Issue
I am new in Django and python. Now I am trying to do web API with Django and python. My GET, POST, and DELETE requests are working, but PUT gives me error:
{ "non_field_errors": [ "No data provided" ] }
(i used Postman)
Here's my code:
Serializer:
from rest_framework import serializers
from .models import Topic
class TopicSerializer(serializers.ModelSerializer):
title = serializers.CharField(max_length=50)
text = serializers.CharField(max_length=500)
class Meta:
model = Topic
fields = [
'title', 'text'
]
def update(self, instance, validated_data):
instance.title = validated_data.get('title', instance.title)
instance.description = validated_data.get('text', instance.description)
instance.save()
return instance
Views:
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Topic
from .serializers import TopicSerializer
class TopicView(APIView):
def get(self, request):
topics = Topic.objects.all()
serializer = TopicSerializer(topics, many=True)
return Response({'topic': serializer.data})
def post(self, request):
topic = request.data
serializer = TopicSerializer(data=topic)
if serializer.is_valid(raise_exception=True):
topic_saved = serializer.save()
return Response({'success': 'Topic {} created successfully'.format(topic_saved.title)})
def put(self, request, pk):
# saved_topic = get_object_or_404(Topic.objects.all())
saved_topic = get_object_or_404(Topic.objects.filter(id=pk))
data = request.data.get('topic')
serializer = TopicSerializer(instance=saved_topic, data=data, partial=True)
if serializer.is_valid(raise_exception=True):
topic_saved = serializer.save()
return Response({
"success": "Topic '{}' updated successfully".format(topic_saved.title)
})
def delete(self, request, pk):
topic = get_object_or_404(Topic.objects.all(), pk=pk)
topic.delete()
return Response({
"message": "Topic with id `{}` has been deleted.".format(pk)
}, status=204)
App URLs:
from django.urls import path
from .views import TopicView
app_name = "rest_test_app"
# app_name will help us do a reverse look-up latter.
urlpatterns = [
path('topics/', TopicView.as_view()),
path('topics/<int:pk>', TopicView.as_view())
]
request body:
{
"title": "pipiska",
"text": "pipiska111"
}
is this because of using wrong methods? (sorry for terrible english)
Solution
Two changes and PUT request will work fine.
One is in the serializers.py file.
Instead of instance.description = validated_data.get('text', instance.description)
change it to instance.text = validated_data.get('text', instance.text)
Another one, as mentioned in the comments, in views.py in put definition use data = request.data
instead of data = request.data.get('topic')
Then give PUT request from Postman with the following request body:
{
"title": "pipiska",
"text": "pipiska111"
}
it will work fine.
Answered By - Mayank Gajpal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.