在Django Rest Framework中找不到资源时返回自定义404错误 [英] Return Custom 404 Error when resource not found in Django Rest Framework

查看:424
本文介绍了在Django Rest Framework中找不到资源时返回自定义404错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Django Rest Framework ,它也是django的新手。当客户端访问未找到的资源时,我想在json中返回自定义 404 错误。

I am learning Django Rest Framework, and also new to django. I want to return a custom 404 error in json when a client will access a resource which was not found.

我的 urls.py 看起来很像这样:

urlpatterns = [
    url(r'^mailer/$', views.Mailer.as_view(), name='send-email-to-admin')
]

其中我只有一个资源,可以通过URI http:// localhost:8000 / mailer /

In which i have only one resource, which can be accessed through URI, http://localhost:8000/mailer/

现在,当客户端访问任何其他URI,例如 http:// localhost:8000 / ,API应该返回 404-Not Found 像这样的错误:

Now, when a client access any other URI like http://localhost:8000/, API should return a 404-Not Found error like this:

{
    "status_code" : 404
    "error" : "The resource was not found"
}

如果合适,请提出一些带有适当代码段的答案。

Please suggest some answer with proper code snippets, if suitable.

推荐答案

您在寻找 handler404

这是我的建议:


  1. 创建一个视图,如果没有URL模式匹配则应调用。

  2. handler404 = path.to.your.view 添加到您的根URLconf。

  1. Create a view that should be called if none of the URL patterns match.
  2. Add handler404 = path.to.your.view to your root URLconf.

操作方法如下:


  1. project.views

from django.http import JsonResponse


def custom404(request, exception=None):
    return JsonResponse({
        'status_code': 404,
        'error': 'The resource was not found'
    })


  • project.urls

    from project.views import custom404
    
    
    handler404 = custom404
    


  • 阅读错误处理以获取更多详细信息。

    Read error handling for more details.

    Django REST框架异常也可能有用。

    这篇关于在Django Rest Framework中找不到资源时返回自定义404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆