【问题标题】:DRF json 404 insetad of html pageDRF json 404 而不是 html 页面
【发布时间】:2018-07-27 21:42:12
【问题描述】:

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

{
    "detail": "Not found."
}

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

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

当我设置 Debug 标志时(在设置的 Ture 中我得到 500,当它设置为 False 404 但在 html 表单中时。

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

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

提前谢谢你

【问题讨论】:

    标签: python django django-rest-framework django-rest-viewsets


    【解决方案1】:

    您应该为 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:

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

    【讨论】:

    • 您好,感谢您的快速回放,但行为仍然相同;(
    • 顺便说一句。主 urls.py 或应用程序一?
    • @Piotr 请检查最后的编辑。我试图使用 DRF 的已实现异常来实现它,但没有奏效。我还在处理函数中添加了exception 参数以与 handler404 绑定
    • 你好彼得,谢谢你现在工作了 :) !无论如何,这是否意味着我们不能使用 restframework 异常?提供翻译的标准例外有什么好处。我不知道为什么,但是当我尝试这样做时: response_data['detail'] = _('Not found.') 我又得到了 500 :(
    • 这仅适用于顶部 urls.py 文件。要调试哪个文件是顶部,您可以在这里.venv/lib/python3.7/site-packages/django/urls/resolvers.py@resolve_error_handler
    猜你喜欢
    • 2018-08-27
    • 2018-12-07
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 2013-10-15
    • 2018-05-25
    • 2012-07-30
    • 2012-09-24
    相关资源
    最近更新 更多