django - 使用 django 和 django Rest 框架在 Rest API 中引发自定义 400 错误请求

标签 django python-3.x django-rest-framework

我想在引发 HTTP 400 错误时返回自定义错误。

这是我的模型:

class User(models.Model):
      fullname = models.CharField(max_length=100)
      phone = models.CharField(max_length=50, unique=True)
      password = models.CharField(max_length=50, default='SOME STRING')

这是我的序列化器类:

class UserSerializer(serializers.ModelSerializer):
      class Meta:
           model = User
           fields = ('id', 'fullname', 'phone', 'password')

这是我在 View 类中的类:

 class RegisterUsers(generics.CreateAPIView):
.
.
.
 serializer = UserSerializer(data={
            "fullname": fullname,
            "phone": phone,
            "password": password
        }
    )

          if not serializer.is_valid(raise_exception=True):
              return

如果我尝试使用相同的号码注册两次,则会出现 400 bad request 错误,如下面的屏幕截图所示:

enter image description here

我想捕获错误并将其解析为如下所示的自定义响应:

enter image description here

谁能帮我解决这个问题吗? 提前致谢。

最佳答案

您可以重写 DRF 自定义异常处理程序方法:

from rest_framework.views import exception_handler
from rest_framework.exceptions import ValidationError


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

  # check that a ValidationError exception is raised
  if isinstance(exc, ValidationError): 
    # This is where you would prepare the 'custom_error_response'
    # and set the custom response data on response object
    response.data = custom_error_response 

  return response

要启用自定义处理程序,请在设置文件中添加 EXCEPTION_HANDLER 设置:

REST_FRAMEWORK = {
'PAGE_SIZE': 20,
'EXCEPTION_HANDLER': 'path.to.your.module.base_exception_handler',

'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication'
)

}

关于django - 使用 django 和 django Rest 框架在 Rest API 中引发自定义 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52780307/

相关文章:

python - 破解 Django 管理员,用于登录/注销的 Hook

django - 如何通过与django中某些属性的关系查询ManyToMany?

django - 反向关系 Django Rest Framework 中的写操作

javascript - Django Rest 框架和 Angular

Django 管理仪表板,有没有办法小写模型名称?

python-3.x - 导入错误 : cannot import name 'OP_NO_TICKET' from 'urllib3.util.ssl_'

python - 在 Python 3 中将二进制字符串转换为字节数组

python - 如果项目位于表中,则返回该项目在表中的位置。 [Py 3.4]

python - 动态修改 Django Rest Framework 中的序列化器字段

python - Django REST 框架验证错误 : 'Enter a valid URL.'