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" } ] } }