Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用django和django Rest框架在Rest API中引发自定义400错误请求_Django_Python 3.x_Django Rest Framework - Fatal编程技术网

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

使用django和django Rest框架在Rest API中引发自定义400错误请求,django,python-3.x,django-rest-framework,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') 这是我的序列化程

我想在引发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')
这是我在视图类中的类:

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

          if not serializer.is_valid(raise_exception=True):
              return
如果我尝试使用同一号码注册两次,会出现400错误请求错误,如下面的屏幕截图所示:

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

有人能帮我解决这个问题吗?
提前感谢。

您可以覆盖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
要启用自定义处理程序,请在设置文件中添加
异常处理程序
设置:

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'
)

}

如果答案有帮助,你应该接受