Django自定义响应成功并失败

时间:2018-02-21 05:29:06

标签: django django-rest-framework

我想为我的一个序列化程序创建成功和失败的自定义响应。现在我只有成功的创建功能

我希望输出显示为默认输出+另外两条消息。

提示符和状态。

例如json数据的输出:如果成功:

promptmsg =“您已成功创建xxx”
status ='200'

如果失败

promptmsg =“您无法创建xxx”
status ='400'

以下是我的观点代码

class ScheduleViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = Schedule.objects.all()
    serializer_class = ScheduleSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid(raise_exception=False):
            return Response({"promptmsg": "You have failed to register an account",
                             "status": "400"}, status=HTTP_400_BAD_REQUEST)

        response = super(ScheduleViewSet, self).create(request, *args, **kwargs)
        response.data['promptmsg'] = 'You have successfully create a book'
        response.data['statuscode'] = '200'
        return response

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        if not serializer.is_valid(raise_exception=False):
            return Response({"promptmsg": "You have failed to register an account",
                             "statuscode": "400"}, status=HTTP_400_BAD_REQUEST)

        # serializer.is_valid(raise_exception=True)
        # self.perform_update(serializer)
        response = super(ScheduleViewSet, self).update(request, *args, **kwargs)
        response.data['promptmsg'] = 'You have successfully create a book'
        response.data['statuscode'] = '200'
        return response

如您所见,如果失败,它只会返回提示符和状态。

如果成功将显示默认响应+ promptmsg + status。

那我该怎么改呢?

2 个答案:

答案 0 :(得分:2)

如果我理解正确,您需要在序列化失败时将错误详细信息添加到自定义错误响应中吗?在这种情况下,您可以使用serializer.errors属性:

if not serializer.is_valid(raise_exception=False):
    errors_details = serializer.errors
    errors_details["promptmsg"] = "You have failed to register an account"
    errors_details["status"] = "400"
    return Response(errors_details, status=HTTP_400_BAD_REQUEST)

答案 1 :(得分:1)

您可以继承Response类:

from rest_framework.response import Response

class MyResponse(Response):
def __init__(self, data=None, status=None, headers=None,
             exception=False, content_type=None):
    # here you can create your custom fields etc...
    result = {
        'status': status,
        'message': data,
    }
    super(MyResponse, self).__init__(data=result, 
                                      headers=headers, 
                                      status=status, 
                                      exception=exception, 
                                      content_type=content_type)

稍后在视图中使用'MyResponse()'代替'Response'