Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.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 rest framework 将Validationerror转换为序列化程序。Django rest框架中的Validationerror_Django Rest Framework - Fatal编程技术网

Django rest framework 将Validationerror转换为序列化程序。Django rest框架中的Validationerror

Django rest framework 将Validationerror转换为序列化程序。Django rest框架中的Validationerror,django-rest-framework,Django Rest Framework,我有以下问题。 我有一个模型级验证,用于检查每次保存时的数据一致性。 在序列化程序中,如果此模型级验证有效,则会生成带有回溯的服务器错误500,而序列化程序中的序列化程序.Validationerror会生成漂亮且干净的400错误,错误消息为json 以将模型级别的Validationerror转换为序列化程序。Validationerror我在序列化程序中使用以下代码 def perform_create(self, validated_data): try: retu

我有以下问题。 我有一个模型级验证,用于检查每次保存时的数据一致性。 在序列化程序中,如果此模型级验证有效,则会生成带有回溯的
服务器错误500
,而序列化程序中的
序列化程序.Validationerror
会生成漂亮且干净的
400错误,错误消息为json

以将模型级别的
Validationerror
转换为
序列化程序。Validationerror
我在序列化程序中使用以下代码

def perform_create(self, validated_data):
    try:
        return super().perform_create(validated_data)
    except exceptions.ValidationError as err:
        raise serializers.ValidationError(
            f'Model level validation assertion -- {str(err)}'
        ) from err
它可以工作,但我不能也不想覆盖每一个序列化程序来将
Validationerror
转换为
序列化程序。验证错误

问题是-是否有任何方法可以捕获所有Validationerror并将其转换为序列化程序。验证错误

from rest_framework.views import exception_handler
from rest_framework.response import Response as DRF_response
from rest_framework import status

from django.core import exceptions
from django.views import View
from django.http import response


def custom_exception_handler(exc: Exception, context: View) -> [response, None]:

    response = exception_handler(exc, context)

    if isinstance(exc, exceptions.ValidationError):
        data = exc.message_dict
        return DRF_response(data=data, status=status.HTTP_400_BAD_REQUEST, )

    return response
我制作了一个定制的错误处理程序,它捕获所有Django标准验证错误并返回DRF风格的响应