this is my serializers.py
from rest_framework import serializers from api.models import Movie
class MovieSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
name=serializers.CharField()
description= serializers.CharField()
viewed = serializers.BooleanField()
def create(self,validated_data):
return Movie.objects.create(**validated_data)
this is my models.py
class Movie(models.Model):
name = models.CharField(max_length=20)
description = models.CharField(max_length=100)
viewed=models.BooleanField(default=True)
def __str__(self):
return self.name
this is views.py
@api_view(['GET','POST'])
def home(request):
if request.method == 'GET':
movies=Movie.objects.all()
serializer=MovieSerializer(movies,many=True)
return Response(serializer.data)
if request.method == 'POST':
serializer=MovieSerializer(data=request.POST)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors)
this is what my output looks like
{
"name": [
"This field is required."
],
"description": [
"This field is required."
]
}
CodePudding user response:
maybe try to change the serializer like that
class MovieSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
name=serializers.CharField()
description= serializers.CharField()
viewed = serializers.BooleanField()
def create(self, name, description, viewed):
return Movie.objects.create(name=name, description=description, viewed=viewed)
CodePudding user response:
As I see from your views.py ,we can see request.POST ,there from request we get data not POST ,POST is API Method.
serializer=MovieSerializer(data=request.POST)
So change that line to this:
serializer=MovieSerializer(data=request.data)
and below you are returning serializer data not POST.
return Response(serializer.data)