如何自定义ModelSerializer的验证错误消息?

时间:2019-08-30 15:12:55

标签: django django-rest-framework django-serializer

我制作了一个名为RegistrationSeriaizer的序列化器,该序列化器继承了ModelSerializer。我想自定义默认错误消息由序列化程序生成。

我想使ModelSrializer生成的验证返回我的自定义错误消息。不是默认值。

# 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']

我希望验证错误消息看起来像这样。

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

1 个答案:

答案 0 :(得分:0)

您有两种声明自定义错误消息的方法,一种是在Model in models.py中定义一个名为error_messages的字典,另一种是在Serializer in serializers.py

您将必须为每个要为其提供自定义错误消息的字段添加此词典。它是使用django作为您的字典中的键和您的消息作为值抛出的错误代码定义的。根据文档:

  

错误消息键包括null,空白,无效,invalid_choice,   唯一且唯一的日期。

您可以将其用作模型字段的参考:

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

如果要在序列化程序中处理此问题,

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