How can IPAddressField error message be changed

Viewed 93

I'm using:

djangorestframework==3.11.0
django==3.0.3

I have changed the CharField Error_message easily, but when I try to change the error message for the IPAddressField:

class InterfaceSerializer(serializers.Serializer):
    ip_address = serializers.IPAddressField(protocol="IPv4",
                                        required=False,
                                        allow_blank=True,
                                        error_messages={'invalid': 'test fail'},
                                        )

The result is always:

{"error_message": {
"ip_address": [
  "Enter a valid IPv4 address."
]}}

And the response is:

2020-03-18 13:13:12,878 : ERROR : response : {'error_message': {'ip_address': [ErrorDetail(string='Enter a valid IPv4 address.', code='invalid')]}}

1 Answers

As you can see that the error message is very specific:

'Enter a valid IPv4 address.'

While looking at the code, I couldn't find such an error message in DRF. It meant that the message is coming from django validator and particularly validate_ipv4_address.

As you mentioned that you are using "string" as input to test it. If you look at the to_internal_value of the IPAddressField, you will notice that the value "string" won't raise any errors there. From there, it goes to validators and produces the message that you see.

Because, validator is directly raising the ValidationError, it doesn't go through the fail method of the serializer. And, hence it is not able to lookup the invalid key in the error messages that was provided in field.

Related