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

时间:2014-05-13 21:40:01

标签: 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."
    ]
}

{
"nick": [
    "Your username is empty"
    ]
}

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

"Username %s already exists", (self.nick)

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

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

这是发送给API的JSON。

{
    "name": "myname",
    "nick":"",
    "type_account":"1",
    "email":"my-email@gmail.com",
    "pass_field":"12345"
}

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

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)

4 个答案:

答案 0 :(得分:3)

这个问题的答案还增加了以下内容@Fiver回答

class userLoginSerializer(serializers.ModelSerializer):

    nick  =  serializers.CharField(error_messages={'required':'Please Type a Username'})
    pass_field = serializers.CharField(error_messages={'required':'Please Type a Password'})

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

答案 1 :(得分:0)

我相信以下内容会起作用:

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

答案 2 :(得分:0)

应该可以在模型级别更改错误消息,但遗憾的是REST Framework尚不支持。 Here是处理问题的一个问题。它包括一个覆盖序列化器中验证器的建议方法。

答案 3 :(得分:0)

您应该使用自定义错误处理程序。按照here进行设置。

您的自定义错误处理程序应如下所示:

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)

# Now add the HTTP status code to the response.
if response is not None:
    for field, value in response.data.items():
        value = ''.join(value)
    response.data = {} # Empty django's custom error
    response.data['detail'] =value  #customize it how you want

return response