问题是创建函数没有调用,只是返回验证布尔值,无论是 true还是false 。 请注意:验证部分工作正常。
代码如下:
Views.py
class TestAPI(APIView):
serializer_request = TestAPISerializer
def post(self,request):
obj = self.serializer_request(data=request.data)
print obj.is_valid()
if obj.is_valid():
obj.save()
return Response(status=status.HTTP_200_OK)
else:
return Response(request_for_demo_ser.errors, status=status.HTTP_400_BAD_REQUEST)
Serializers.py
class TestAPISerializer(serializers.ModelSerializer):
class Meta:
model = TestDemo
fields = ('name')
# THIS FUNCTION IS NOT AT ALL CALLING.
def create(self, validated_data):
name = validated_data['name']
return TestDemo.objects.create(name=name)
答案 0 :(得分:1)
你忘了保存。
obj = self.serializer_request(data=request.data)
print obj.is_valid()
if obj.is_valid():
obj.save() # add this line
# Change code to 201
return Response(status=status.HTTP_201_CREATED)
# return Response(status=status.HTTP_200_OK)