Salah Hegazi
Salah Hegazi

Reputation: 41

How to customize the validation error messages of ModelSerializer?

I made a serializer named RegistrationSeriaizer that inherits ModelSerializer. and I want to custom default error messages generates by the serializer.

I want to make validation generated by ModelSrializer to return a my custom error messages. not the default.

# This is my model.
class Person(AbstractBaseUser):
"""
A custom User model that represents users
"""
    GENDER_CHOICES = [
        ('M', 'Male'),
        ('F', 'Female'),
    ]
    first_name = models.CharField(_("First name of User"), max_length=50)
    last_name = models.CharField(_("Last name of User"), max_length=50)
    country_code = CountryField(_("Country code of User"), max_length=10)
    # Using phonenumber_field third package to
    # define phonenumber in E.164 format
    phone_number = PhoneNumberField(_("Phone number of User"), unique=True)
    gender = models.CharField(_("Gender of User"), max_length=1,
                          choices=GENDER_CHOICES)
    birth_date = models.DateField(_("Birth date of User"))
    avatar = models.ImageField(_("Image of User"), upload_to='images/')
    email = models.EmailField(_("Email of User"), blank=True, unique=True,
                          max_length=255)
    objects = PersonManager()
    USERNAME_FIELD = 'phone_number'
    REQUIRED = [
        'first_name', 'last_name',
        'country_code', 'gender',
        'birth_date', 'avatar',
    ]

    def __str__(self):
        return self.first_name + ' ' + self.last_name




# This is my serializer
class RegistrationSerializer(serializers.ModelSerializer):

    class Meta:
        model = Person
        exclude = ['last_login']

I want the validation error messages to look like this.

{ "errors": { "first_name": [ { "error": "blank" } ], "last_name": [ { "error": "blank" } ], "country_code":[ { "error": "inclusion" } ], "phone_number": [ { "error": "blank" }, { "error": "not_a_number" }, { "error": "not_exist" }, { "error": "invalid" }, { "error": "taken" }, { "error": "too_short", "count": 10 }, { "error": "too_long", "count": 15 } ], "gender": [ { "error": "inclusion" } ], "birthdate": [ { "error": "blank" },{ "error": "in_the_future" } ], "avatar": [ { "error": "blank" }, { "error": "invalid_content_type" } ], "email": [{ "error": "taken" }, { "error": "invalid" } ] } }

Upvotes: 1

Views: 1981

Answers (1)

Mehak
Mehak

Reputation: 961

You have two ways of declaring your custom error messages, one by defining a dictionary named as error_messages in your Model in models.py, the other is by defining it in your Serializer in serializers.py

You will have to add this dictionary for every field that you want a custom error message for. It is defined using the error code that django throws as a key in your dictionary and your message as value. As per the documentation:

Error message keys include null, blank, invalid, invalid_choice, unique, and unique_for_date.

You can use this for your reference, for your model field:

first_name = models.CharField(_("First name of User"), max_length=50, error_messages = {"blank": "Invalid name entered"})

And if you want to handle this in serializers:

first_name = serializers.CharField(error_messages = {"blank": "Invalid name entered"})

Upvotes: 2

Related Questions