Django Rest Framework custom response message

2020-08-20 11:09发布

I have two questions about Django Rest Framework response message

1.

When use generics.ListCreateAPIView or RetrieveDestroyAPIView , usually return a resource

For example ,call /map/ with POST Method The result will like a object :

{
    "x_axis": "23",
    "y_axis": "25",
    "map_id": 1,
}

I want to know can I edit this message to custom like below?

{"Success":"msg blablabla"}

2.

When I use serializers.ValidationError , I can write my custom message if I use raise serializers.ValidationError("map_id does not exist") The response message will be

{"map_id":["map_id does not exist"]}

Can I edit this part to custom like below?

{"FAIL":"map_id does not exist"}

I want to know this because front-end don't want this format, They like :

{"Success":"msg blablabla"}
{"Fail":"msg blablabla"}
{"USERNAME_DUPLICATE":1001}
{"FIELD_REQUIRED":1002}

So they can be more convenient to tell user the operate error cause ?

1条回答
神经病院院长
2楼-- · 2020-08-20 12:03

1 Overwrite the create method on the view and put something like this:

def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response({"Success": "msb blablabla"}, status=status.HTTP_201_CREATED, headers=headers)

2 In the code above, change raise_exception to False and return whatever you want if the serializer is not valid. i.e.:

def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid(raise_exception=False):
            return Response({"Fail": "blablal", status=status.HTTP_400_BAD_REQUEST)

        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response({"Success": "msb blablabla"}, status=status.HTTP_201_CREATED, headers=headers)

You are using CBV so you'll be able to create your custom generic classes that extends DRF's classes, and DRY

however, I'd say that you shouldn't add "success" or "fail" in your responses... if the http code is 2xx the user will know it was OK, 4xx when the request has a problem and 5xx when there was a error on your code (or the server), you don't need to repeat that information on the body of your response, just use the HTTP status codes

Hope this helps

查看更多
登录 后发表回答