如果GET或POST成功失败,如何将友好消息返回给我的客户端?
serializers.py
class BrandSerializer(serializers.ModelSerializer):
"""
Class to serialize Brand objects
"""
class Meta:
model = Brand
fields = '__all__'
read_only_fields = 'id'
class BrandSignupSerializer(serializers.Serializer):
"""
Create Brand profile
"""
name = serializers.CharField(required=True, write_only=True)
brand = serializers.CharField(required=True, write_only=True)
email = serializers.EmailField(required=True, write_only=True)
phone = serializers.CharField(required=True, write_only=True)
website = serializers.CharField(required=True, write_only=True)
class Meta:
model = Brand
fields = ('name', 'brand', 'email', 'phone', 'website')
unique = 'email'
def create(self, validated_data):
brand = Brand.objects.create(**validated_data)
brand.save()
return brand
def update(self, instance, validated_data):
pass
views.py
class BrandList(generics.ListAPIView):
"""
List all Brands
HTTP: GET
"""
queryset = Brand.objects.all()
serializer_class = BrandSerializer
class BrandDetail(generics.RetrieveUpdateDestroyAPIView):
"""
List one Brand
HTTP: GET
"""
queryset = Brand.objects.all()
serializer_class = BrandSerializer
class BrandSignup(generics.CreateAPIView):
"""
Brand signup
HTTP POST
"""
queryset = Brand.objects.all()
serializer_class = BrandSignupSerializer
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
return Response(data=serializer.data, status=status.HTTP_201_CREATED)
答案 0 :(得分:1)
我相信您可以在Response
中传递一个dict,您可以在其中插入自定义信息,例如序列化数据,自定义消息,状态和状态代码作为字符串:
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if (serializer.is_valid(raise_exception=True)) :
response_details = {
'data': serializer.data,
'message': "Your custom success message",
'code': "201",
'status': HTTP_201_CREATED
}
else :
response_details = {
'data': serializer.errors,
'message': "Your custom error message",
'code': "400",
'status': HTTP_400_BAD_REQUEST
}
return Response(response_details, status=response_details['status'])
然后,您可以在呈现数据的视图中访问与您的回复一起传递的字典的不同元素,例如data
或message
。