Custom format for serializer ValidationError

Viewed 278

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?

1 Answers

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.

Related