序列化器 ValidationError 的自定义格式

发布于 2025-01-11 12:29:14 字数 744 浏览 0 评论 0原文

我在我的序列化器之一中有一个自定义对象级验证器:

def validate(self, data):
    # some checks on token
    # set token to True or False
    
    if not token:
        raise serializers.ValidationError(
            {
                "status": "failed",
                "message": _("token is not valid"),
            }
        )
    
    return data

我期望得到的输出是这样的:

{
    "status": "failed",
    "message": "token is not valid"
}

但是,我实际得到的是:

{
    "status": [
        "failed"
    ],
    "message": [
        "token is not valid"
    ]
}

有没有办法实现我正在寻找的东西?

Iv'e got a custom object-level validator in one of my serializers:

def validate(self, data):
    # some checks on token
    # set token to True or False
    
    if not token:
        raise serializers.ValidationError(
            {
                "status": "failed",
                "message": _("token is not valid"),
            }
        )
    
    return data

What I expect to get as an output is this:

{
    "status": "failed",
    "message": "token is not valid"
}

However, what I'm actually getting is:

{
    "status": [
        "failed"
    ],
    "message": [
        "token is not valid"
    ]
}

Is there anyway to achieve what I'm looking for?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何以笙箫默 2025-01-18 12:29:14

创建自定义 ValidatorError 类:

from rest_framework import serializers, status
from rest_framework.exceptions import APIException


class PlainValidationError(APIException):
    status_code = status.HTTP_400_BAD_REQUEST
    default_detail = _("Invalid input.")
    default_code = "invalid"

    def __init__(self, detail=None, code=None):
        if not isinstance(detail, dict):
            raise serializers.ValidationError("Invalid Input")
        self.detail = detail

不要使用 serializers.ValidationError,而是使用自定义 ValidationError 类:

def validate(self, data):
    # some checks on token
    # set token to True or False
    
    if not token:
        raise PlainValidationError(
            {
                "status": "failed",
                "message": _("token is not valid"),
            }
        )
    
    return data

它并不完美,但它适合我。

Create a custom ValidatorError class:

from rest_framework import serializers, status
from rest_framework.exceptions import APIException


class PlainValidationError(APIException):
    status_code = status.HTTP_400_BAD_REQUEST
    default_detail = _("Invalid input.")
    default_code = "invalid"

    def __init__(self, detail=None, code=None):
        if not isinstance(detail, dict):
            raise serializers.ValidationError("Invalid Input")
        self.detail = detail

Instead of using serializers.ValidationError use your custom ValidationError class:

def validate(self, data):
    # some checks on token
    # set token to True or False
    
    if not token:
        raise PlainValidationError(
            {
                "status": "failed",
                "message": _("token is not valid"),
            }
        )
    
    return data

It's not perfect but it does the job for me.

深居我梦 2025-01-18 12:29:14

通过在视图端验证您的令牌,您可以更轻松地实现此目的。例如,您的视图将如下所示:

# Your view
class MyView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(
            data=request.data, context={"request": request}
        )
        serializer.is_valid()
        token = serializer.validated_data["token"]
        if not token:
            return Response(
                data={"status": "failed", "message": _("token is not valid")},
                status=401
            )
        # The rest of your code below

您可以设置该行
如果您还有其他验证要做,请将 serializer.is_valid() 更改为 serializer.is_valid(raise_exception=True)
我希望这会有所帮助

It will be easier for you to achieve this by validating your token at the view side instead. For example your view will look like this:

# Your view
class MyView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(
            data=request.data, context={"request": request}
        )
        serializer.is_valid()
        token = serializer.validated_data["token"]
        if not token:
            return Response(
                data={"status": "failed", "message": _("token is not valid")},
                status=401
            )
        # The rest of your code below

You can set the line
serializer.is_valid() to serializer.is_valid(raise_exception=True) if you have other validations to do.
I hope this will help

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文