ameerabdulaziz
ameerabdulaziz

Reputation: 25

How to override the CharField max_length validation error message that will be responded when sending a post request via API?

I have a Customer model that has a mobile_phone field. When I send a post request via API to create a customer with a mobile phone value more than 15 I get that validation error message "Ensure this field has no more than 15 characters.". I don't like this message and I would like to override it. Is there a solution to do so?

class Customer(models.Model):
    ...
    name = models.CharField(_('full name'), max_length=200)
    mobile_phone = models.CharField(_('mobile phone'), max_length=15, blank=True, null=True)
    ...

I tried to do something like that

def validate_value_lt_fifteen(value):
    if value > 15:
        raise ValidationError(_('Ensure that the mobile phone has no more than 15 characters.'), params={'value': value})


class Customer(models.Model):
    ...
    name = models.CharField(_('full name'), max_length=200)
    mobile_phone = models.CharField(_('mobile phone'),
                                    max_length=15, blank=True, null=True, validators=[validate_value_lt_fifteen])
    ...

But unfortunately, it does not solve the problem. On the contrary, it shows both error messages together. "Ensure this field has no more than 15 characters." and "Ensure that the mobile phone has no more than 15 characters."

Upvotes: 2

Views: 1456

Answers (1)

minglyu
minglyu

Reputation: 3327

ModelForm

Override the default error message for validators would solve your problem

class CustomerForm(models.ModelForm):
    class Meta:
        error_messages = {
            'mobile_phone': {
                'max_length': _('Ensure that the mobile phone has no more than 15 characters.'),
            }
        }

REST API

If you are using rest_framework, you could provide the error_messages to the Field to override the default error message

my_default_errors = {'max_length': _('Ensure that the mobile phone has no more than 15 characters.')}

class CustomerSerializer(serializers.Serializer):
    mobile_phone = serializer.CharField(error_messages=my_default_errors)

# ModelSerializer
class CustomerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Customer
        extra_kwargs = {"mobile_phone": {"error_messages": {"max_length": _('Ensure that the mobile phone has no more than 15 characters.')}}}

Upvotes: 3

Related Questions