Django rest_framework custom error message

陌路散爱 提交于 2021-02-04 19:50:26

问题


I have a API endpoint where it will do input validation using rest_framework's serializer.is_valid() where it will return custom error message and response.

serializer = FormSerializer(data=data)
if not serializer.is_valid(raise_exception=False):
    return Response({"Failure": "Error"}, status=status.HTTP_400_BAD_REQUEST)

Is it possible to populate validation errors without using the generic response provided by raise_exception=True? I am trying to avoid using the generic response as it will display all the validation errors if there are more than one error.

The response will be something like

return Response(
     {
          "Failure": "Error", 
          "Error_list": {"field1": "This field is required"}
     },
     status=status.HTTP_400_BAD_REQUEST
) 

回答1:


Create a Custom Exception class as,

from rest_framework.exceptions import PermissionDenied
from rest_framework import status


class MyCustomExcpetion(PermissionDenied):
    status_code = status.HTTP_400_BAD_REQUEST
    default_detail = "Custom Exception Message"
    default_code = 'invalid'

    def __init__(self, detail, status_code=None):
        self.detail = detail
        if status_code is not None:
            self.status_code = status_code


Why I'm inherrited from PermissionDenied exception class ??
see this SO post -- Why DRF ValidationError always returns 400

Then in your serializer, raise exceptions as,

class SampleSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = SampleModel

    def validate_age(self, age):  # field level validation
        if age > 10:
            raise MyCustomExcpetion(detail={"Failure": "error"}, status_code=status.HTTP_400_BAD_REQUEST)
        return age

    def validate(self, attrs): # object level validation
        if some_condition:
            raise MyCustomExcpetion(detail={"your": "exception", "some_other": "key"}, status_code=status.HTTP_410_GONE)
        return attrs


age and name are two fields of SampleModel class


Response will be like this


By using this method,
1. You can customize the JSON Response
2. You can return any status codes
3. You don't need to pass True in serializer.is_valid() method (This is not reccomended)




回答2:


You can write custom error handler:

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if response is not None:
        response.data['Failure'] = 'Error'

    return response



回答3:


A simple way is to use one of the exception messages, eg NotFound. See docs

# views.py
from rest_framework.exceptions import NotFound

class myview(viewsets.ModelViewSet):
    def perform_create(self, serializer):
        raise NotFound("My text here")

That will return a 404 and change the response to your text

HTTP 404 Not Found
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
    "detail": "my text here"
}


来源:https://stackoverflow.com/questions/51665260/django-rest-framework-custom-error-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!