自定义NotFound异常--- Django REST Framework

时间:2017-04-13 09:42:09

标签: python django django-rest-framework

假设使用person模型,ModelSerializer和相应ReadOnlyModelViewSet的最小应用程序。

数据库中只存在一个条目,因此在正确请求/person/1时,响应正确为:

{
  "name": "RandomName1"
}

请求/person/2时,响应为:

{
  "detail": "Not found."
}

我想自定义此内容。

即使我阅读documentation,我也不清楚如何自定义此内容。

我应该澄清一下,我希望根据视图来定制这个。例如/person/2应返回:

{
  "detail": "Person 2 was not found."
}

/address/3应该返回:

{
  "detail": "Address 3 was not found."
}

1 个答案:

答案 0 :(得分:3)

听起来您想要处理具有404状态代码的响应。修改链接文档中的示例:

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response.data['status_code'] == 404:
        try:
            response.data['detail'] = "{name} {id} was not found.".format(
                name=context['view'].verbose_name,
                id=context['kwargs']['id']  # this may need tweaking
            )
        except AttributeError:
            pass

    return response

然后将相应的verbose_name添加到您的视图中。