Django rest_framework custom error message

前端 未结 3 736
梦谈多话
梦谈多话 2021-01-15 15:27

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.

3条回答
  •  甜味超标
    2021-01-15 15:53

    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"
    }
    

提交回复
热议问题