如何配置Django Rest Framework以返回自定义文本的错误

Edd*_*Paz 10 django django-rest-framework

我想在向数据库添加新项时自定义JSON响应,它返回以下内容.

HTTP 400 BAD REQUEST 
Content-Type: application/json Vary: 
Accept Allow: POST, OPTIONS

{
"nick": [
    "Users with this Nick already exists."
    ]
}
Run Code Online (Sandbox Code Playgroud)

{
"nick": [
    "Your username is empty"
    ]
}
Run Code Online (Sandbox Code Playgroud)

我希望它返回(此用户名已存在,请使用其他用户名.)

要么

"Username %s already exists", (self.nick)
Run Code Online (Sandbox Code Playgroud)

我使用了以下示例,但如果值为空或无效,则无效.

def validate_title(self, attrs, source):
    """
    Check that the blog post is about Django.
    """
    value = attrs[source]
    if "django" not in value.lower():
        raise serializers.ValidationError("Blog post is not about Django")
    return attrs
Run Code Online (Sandbox Code Playgroud)

这是发送到API的JSON.

{
    "name": "myname",
    "nick":"",
    "type_account":"1",
    "email":"my-email@gmail.com",
    "pass_field":"12345"
}
Run Code Online (Sandbox Code Playgroud)

serializers.py

class userSerializer(serializers.ModelSerializer):

    class Meta:
        model = users
        fields = ('nick', 'email', 'pass_field', 'type_account')

    def validate_nick(self, attrs, source):

        value = attrs[source]
        if not value:
            raise serializers.ValidationError('Username cannot be empty')
        elif self.Meta.model.objects.filter(nick=value).exists():
            raise serializers.ValidationError("Username "+value+" is in use")
        return attrs
Run Code Online (Sandbox Code Playgroud)

views.py

@api_view(['POST'])
def user_add(request):
    """
    Saves a new user on the database
    """

    if request.method == 'POST':

        serializer = userSerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Run Code Online (Sandbox Code Playgroud)

Fiv*_*ver 1

我相信像下面这样的东西会起作用:

def validate_nick(self, attrs, source):
    """
    Check that 'nick' is not already used or empty.
    """
    value = attrs[source]
    if not value:
        raise serializers.ValidationError("Nick cannot be empty!")
    elif self.Meta.model.objects.filter(nick=value).exists():
        raise serializers.ValidationError("Username %s already exists", value)
    return attrs
Run Code Online (Sandbox Code Playgroud)