How Configure Django Rest Framework to return erro

2019-04-21 05:38发布

I want to customize the JSON response when adding a new item to the database it returns the following.

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

{
"nick": [
    "Users with this Nick already exists."
    ]
}

and

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

I want it to return (This username already exists, please use a different one.)

or

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

I used the following sample but does not work if the value is empty or invalid.

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

this is the JSON that gets sent to the API.

{
    "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条回答
闹够了就滚
2楼-- · 2019-04-21 06:05

I believe something like the following will work:

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
查看更多
孤傲高冷的网名
3楼-- · 2019-04-21 06:19

You should use custom error handler. Follow here to setup.

Your Custom error handler should be like this:

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
查看更多
干净又极端
4楼-- · 2019-04-21 06:29

the answer to this question also adds the following as @Fiver answered

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')
查看更多
戒情不戒烟
5楼-- · 2019-04-21 06:31

It should be possible to alter the error messages at the model level, but unfortunately REST Framework doesn't support that yet. Here is an issue dealing with the problem. It includes a suggested method for overriding the validator in the serializer.

查看更多
登录 后发表回答