我遵循这个https://stackoverflow.com/a/31381075/10087274是因为我希望当url不存在时,json会显示错误,但问题是当我在url分派器中添加handler404时,会得到服务器错误500,这是我的项目url:
from django.urls import path, include
from django.conf.urls import handler404
from api.exception import custom404
handler404 = custom404
urlpatterns = [
path('api/v1/', include('acl.urls')),
]我的项目文件夹中有exception.py (接近settings.py),包含以下内容:
from django.http import JsonResponse
def custom404(request):
return JsonResponse({
'status_code': 404,
'error': 'The resource was not found'
})我不知道如何解决我的问题
发布于 2022-05-25 03:16:11
好的django rest框架是开源的,所以如果您想复制某些行为,您可以阅读代码并选择您喜欢的内容。例如,您可以看到drf文档中提供的通用错误视图(自定义服务器和坏请求错误视图)位于rest_framework内部的exceptions.py中,您可以查找这里并查看如何完成它。
创建一个自定义404视图,如下所示:
def not_found(request, exception, *args, **kwargs):
""" Generic 404 error handler """
data = {
'error': 'Not Found (404)'
}
return JsonResponse(data, status=status.HTTP_404_NOT_FOUND)https://stackoverflow.com/questions/56089107
复制相似问题