How to change validation error responses in DRF?

后端 未结 3 970
执笔经年
执笔经年 2021-02-19 00:03

I want to change the JSON, which rest_framework or django returns when a validation error occures.

I will use one of my views as example, but I want to change error mess

相关标签:
3条回答
  • 2021-02-19 00:48
    if not serializer.is_valid(raise_exception=False)
        return Response(serializer.errors.values(), status=status.HTTP_400_BAD_REQUEST)
    
    0 讨论(0)
  • 2021-02-19 00:52

    The default structure of DRF when handling errors is something like this:

    {"email": ["This field is required."]}
    

    And you can change this structure to your need by writing a custom exception handler.

    Now let's say you want to achieve the following structure:

    {"errors": [{"field": "email", "message": "This field is required."}]}
    

    Your custom exception handler could be something like this:

    from rest_framework.views import exception_handler
    
    
    def custom_exception_handler(exc, context):
        # Call REST framework's default exception handler first,
        # to get the standard error response.
        response = exception_handler(exc, context)
    
        # Update the structure of the response data.
        if response is not None:
            customized_response = {}
            customized_response['errors'] = []
    
            for key, value in response.data.items():
                error = {'field': key, 'message': value}
                customized_response['errors'].append(error)
    
            response.data = customized_response
    
        return response
    
    0 讨论(0)
  • 2021-02-19 00:56

    The easiest way to change the error style through all the view in your application is to always use serializer.is_valid(raise_exception=True), and then implement a custom exception handler that defines how the error response is created.

    0 讨论(0)
提交回复
热议问题