Python django rest_框架自定义异常错误

Python django rest_框架自定义异常错误,python,django,django-rest-framework,Python,Django,Django Rest Framework,我是django rest_框架的新手,尝试在django!中创建自定义的错误响应 在经历了这些之后,一切看起来都很简单,但是当我尝试添加自定义异常时,导入错误会出现 设置.py REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'project.restapi.utils.custom_exception_handler' } 强求恐怖 异常值: 无法为API设置“异常处理程序”导入“project.restapi.utils.custom\u exc

我是django rest_框架的新手,尝试在django!中创建自定义的错误响应

在经历了这些之后,一切看起来都很简单,但是当我尝试添加自定义异常时,导入错误会出现

设置.py

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'project.restapi.utils.custom_exception_handler'
}
强求恐怖 异常值:
无法为API设置“异常处理程序”导入“project.restapi.utils.custom\u exception\u handler”。AttributeError:模块“project.restapi.utils”没有“custom\u exception\u handler”属性

自定义\u异常\u处理程序.py

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status_code'] = response.status_code

    return response
model.py

class Users(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def retrieve(self, request, *args, **kwargs):
        # call the original 'list' to get the original response
        response = super(Users, self).retrieve(request, *args, **kwargs) 

        response.data = {"collection": {"data": response.data},"statusCode":response.status_code,"version":"1.0"}
        # customize the response data
        if response is not None:
            return response
        else:
            # return response with this custom representation
            response.data = {"collection": {"data": response.data},"statusCode":response.status_code,"version":"1.0","error":response.exception}
            return response
因此,上面的模型工作得很好,除了当我试图点击不在数据库中的用户时,会引发错误-找不到,所以我尝试自定义找不到对我自己有意义的用户。就这样

我试着整理,但很难做到

Django版本:2.1.5
Python-3.7.0

因为您的
自定义异常处理程序
位于名为
自定义异常处理程序.py
的文件中。您可以尝试将
异常处理程序
设置更改为:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'project.restapi.utils.custom_exception_handler.custom_exception_handler'
}

这可能是导入/模块问题。您应该在问题中包括project.restapi.utils的内容。没有这一点,很难判断问题出在哪里。您可能需要在该文件夹中有一个
\uuu init\uuuuuuuuuuuuuuuuuuuupy
文件,并在那里导入
自定义异常处理程序
。发布自定义异常处理程序.py代码后,将尝试从
项目.restapi.utils.custom异常处理程序
中导入
自定义异常处理程序
函数(即最后一个点之后的部分)。在您的尝试中,它试图从
project.restapi.utils
导入
自定义\u异常\u处理程序
函数(val,设置\u name,e.。\uu class\uu name,e)。这实际上非常重要!!