如何更改 DRF 中的验证错误响应?

新手上路,请多包涵

我想更改发生验证错误时 rest_framework 或 Django 返回的 JSON。

我将使用我的一个视图作为示例,但我想更改所有视图的错误消息。所以假设我有这个视图意味着登录用户,提供电子邮件和密码。如果这些都是正确的,它返回 access_token。

如果我只发布密码,它会返回错误 400:

 {"email": ["This field is required."]}

如果密码和电子邮件不匹配:

 {"detail": ["Unable to log in with provided credentials."]}

我想要的更像是:

 {"errors": [{"field": "email", "message": "This field is required."}]}

{"errors": [{"non-field-error": "Unable to log in with provided credentials."}]}

现在这是我的 观点

 class OurLoginObtainAuthToken(APIView):
    permission_classes = (AllowAny,)
    serializer_class = serializers.AuthTokenSerializer
    model = Token

    def post(self, request):
        serializer = self.serializer_class(data=request.DATA)
        if serializer.is_valid():
            #some magic
            return Response(token)
        return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)

我可以访问 serializer.errors 并更改它们,但看起来 只能通过这种方式访问字段错误,如何更改在我的序列化程序的验证方法中创建的验证错误?

这是我的 序列化 程序(它与 rest_framework.authtoken.serializers.AuthTokenSerializer 是同一个序列化程序)但已编辑,因此身份验证不需要用户名但需要电子邮件:

 class AuthTokenSerializer(serializers.Serializer):
    email = serializers.CharField()
    password = serializers.CharField()

    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')
        if email and password:
            user = authenticate(email=email, password=password)

            if user:
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise ValidationError(msg)
                attrs['user'] = user
                return attrs
            else:
                msg = _('Unable to log in with provided credentials.')
                raise ValidationError(msg)
        else:
            msg = _('Must include "username" and "password"')
            raise ValidationError(msg)

或者也许有一种完全不同的方法?我将非常感谢任何想法。

原文由 Matúš Bartko 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 547
2 个回答

通过应用程序中的所有视图更改错误样式的最简单方法是始终使用 serializer.is_valid(raise_exception=True) ,然后实施定义错误响应创建方式的 自定义异常处理程序

原文由 Tom Christie 发布,翻译遵循 CC BY-SA 3.0 许可协议

DRF 在处理错误时的默认结构是这样的:

 {"email": ["This field is required."]}

您可以通过编写 自定义异常处理程序 来根据需要更改此结构。

现在假设您要实现以下结构:

 {"errors": [{"field": "email", "message": "This field is required."}]}

您的自定义异常处理程序可能是这样的:

 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)

    # Update the structure of the response data.
    if response is not None:
        customized_response = {}
        customized_response['errors'] = []

        for key, value in response.data.items():
            error = {'field': key, 'message': value}
            customized_response['errors'].append(error)

        response.data = customized_response

    return response

原文由 Abdullah Alharbi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题