Search code examples
pythondjangodjango-formsdjango-validation

Django: Change the error message for validate_ipv46_address


I want to change the error message of the validator validate_ipv46_address.

This is my code in my forms.py:

class IPAddressForm(forms.ModelForm):
    ip_address = forms.CharField(validators=[validate_ipv46_address])

    class Meta:
        # ...

    def __init__(self, *args, **kwargs):
         super(IPAddressForm, self).__init__(*args, **kwargs)


    def clean_ip_address(self):
         # i check other stuff

and i want to change the messege of the validate_ipv46_address, but it hasn't a message argument like validate_ipv46_address(message='').

Or do I have to write my own validator? But this also doesn't work.

class my_validate_ipv4_address(validate_ipv46_address):
    message = 'test'

Solution

  • Quick check in source reveals that you need to wrap it like this:

    def my_validate_ipv46_address(value):
        try:
            validate_ipv46_address(value)
        except ValidationError:
            raise ValidationError(_('your message here'), code='invalid')
    

    What it does is that it catches validation error raised by Django's validator and you provide it with your own exception message. Please note, that you would ignore original message returned from validator - it may be better to still utilise it to give proper information about the cause of failure of validation.