DjangoRestFramework忽略自定义错误消息

时间:2015-10-02 04:00:43

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

这是我的UserExtendedSerializer:

class UserExtendedSerializer(serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
            super(UserExtendedSerializer, self).__init__(*args, **kwargs) # call the super() 
            for field in self.fields: # iterate over the serializer fields
                self.fields[field].error_messages['required'] = 'Enter a valid %s.'%field # set the custom error message
                self.fields[field].error_messages['invalid'] = 'Select a valid %s.'%field # set the custom error message
    class Meta:
        model = UserExtended
        fields = ('country',)

这是我的models.py:

class Country(models.Model):
    countryName = models.CharField(max_length=50, unique=True)
    countryCode = models.CharField(max_length=10, unique=True)

class UserExtended(models.Model):
    user = models.OneToOneField(User)
    country = models.ForeignKey(Country)

我的问题是,当用户提交无效类型(Django期望一个整数/ pk值,但假设用户提交字符串“a”)时,Django向前端发送错误,说“不正确的类型。预期pk价值,收到清单。“即使我在我的序列化程序中覆盖了“无效”错误消息。为什么发送到前端的错误消息不是“选择有效的国家/地区”,而是“不正确的类型。预期的pk值,收到的列表。”代替?

1 个答案:

答案 0 :(得分:1)

首先执行Django验证,因此您可以将country field设置为只读并阻止django模型验证,然后在update/create方法中验证国家/地区并在需要时引发错误。您还需要创建CountrySerializer

class CountrySerializer(serializers.ModelSerializer):
    #country serializer fields goes here

class UserExtendedSerializer(serializers.ModelSerializer):
        country = CountrySerializer(read_only=True)
        class Meta:
            model = UserExtended
            fields = ('country',)

        def check_country(self):
            request = self.context['request']
            data = request.data
            country_data = data.get('country'):
            #Validated your country data
            #valid_country = .....
            if not valid_country:
                 raise serializers.ValidationError("Select a valid country")


        def create(self,validated_data):

            self.check_country()
            super(UserExtended,self).create(self,validated_data)

        def update(self,instance,validated_data):

            self.check_country()
            super(UserExtended,self).update(self,instance,validated_data)