DRF json 404 html页面的insetad

2024-10-02 14:16:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用DRF响应替换默认的django404(以及将来的其他响应),尽可能简单,只返回(标准DRF响应):

{
    "detail": "Not found."
}

所以我在我的网址.py文件。在

^{pr2}$

当我设置调试标志时(在setture中,我得到500,当设置为False 404时,但以html形式。在

我读过这里的博士:http://www.django-rest-framework.org/api-guide/exceptions/但说实话,我不知道如何将其付诸实践。在

这看起来很简单,但不知怎么的我没能实现(上面的代码来自另一个SO线程)。在

提前谢谢你


Tags: 文件pyfalse标准标志htmlnot形式
1条回答
网友
1楼 · 发布于 2024-10-02 14:16:59

您应该为404创建一个自定义视图,然后才能使用它。 例如:

views.py中:

from django.http import HttpResponseNotFound
import json

def error404(request, exception):
    response_data = {}
    response_data['detail'] = 'Not found.'
    return HttpResponseNotFound(json.dumps(response_data), content_type="application/json")

然后在urls.py中:

^{pr2}$

相关问题 更多 >

    热门问题