Django Rest Framework针对404错误的自定义消息

Aru*_*run 3 python django django-rest-framework

我有一个基于通用类的视图:

class ProjectDetails(mixins.RetrieveModelMixin,
                     mixins.UpdateModelMixin,
                     generics.GenericAPIView):
    queryset = Project.objects.all()
    # Rest of definition
Run Code Online (Sandbox Code Playgroud)

在我urls.py,我有:

urlpatterns = [
    url(r'^(?P<pk>[0-9]+)/$', views.ProjectDetails.as_view())
]
Run Code Online (Sandbox Code Playgroud)

当使用不存在的id调用API时,它将返回HTTP 404包含内容的响应:

{
    "detail": "Not found."
}
Run Code Online (Sandbox Code Playgroud)

是否可以修改此响应?

我只需要为此视图自定义错误消息.

vis*_*ell 8

此解决方案影响所有视图:

当然,您可以提供自定义异常处理程序:自定义异常处理

from rest_framework.views import exception_handler
from rest_framework import status

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)

    # Now add the HTTP status code to the response.
    if response.status_code == status.HTTP_404_NOT_FOUND:
        response.data['custom_field'] = 'some_custom_value'

    return response
Run Code Online (Sandbox Code Playgroud)

当然你可以跳过默认值rest_framework.views.exception_handler并使其完全原始.

注意:记得提到你的处理程序 django.conf.settings.REST_FRAMEWORK['EXCEPTION_HANDLER']

特定视图的解决方案:

from rest_framework.response import Response
# rest of the imports

class ProjectDetails(mixins.RetrieveModelMixin,
                     mixins.UpdateModelMixin,
                     generics.GenericAPIView):
    queryset = Project.objects.all()

    def handle_exception(self, exc):
        if isinstance(exc, Http404):
            return Response({'data': 'your custom response'}, 
                            status=status.HTTP_404_NOT_FOUND)

        return super(ProjectDetails, self).handle_exception(exc)
Run Code Online (Sandbox Code Playgroud)