Skip to main content
 首页 » 编程设计

python之DRF json 404 而不是 html 页面

2025年01月19日10傻小

我想用 DRF 响应替换默认的 django 404(以及 future 的其他),尽可能简单,只是为了返回(标准 DRF 响应):

{ 
    "detail": "Not found." 
} 

所以我把这段代码放在我的 url.py 文件中。

from rest_framework.exceptions import NotFound 
from django.conf.urls import handler404 
handler404 = NotFound 

当我设置 Debug 标志时(在 set Ture 中我得到 500,当将它设置为 False 404 但以 html 形式时。

我在这里阅读了文档:http://www.django-rest-framework.org/api-guide/exceptions/但老实说,我不知道如何将其变为现实。

这似乎很容易,但不知何故我未能实现这一点(以上代码来自其他 SO 线程)。

提前致谢

请您参考如下方法:

您应该为 404 创建自定义 View 然后使用它。 例如:

在 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 中:

from django.conf.urls import handler404 
 
from yourapp.views import error404 
 
handler404 = error404