Django Rest Framework:如何设置自定义名称表单non_field_errors?

时间:2016-10-23 12:24:42

标签: django django-rest-framework

我正在验证在我网站上注册的用户是否给我一个唯一的地址(城市,街道,街道号码等),当它不是唯一的时候,那么我正在筹集serializers.ValidationError

class UserSerializer(serializers.ModelSerializer):
   def validate(self, attrs):
        city = attrs['city']
        street = attrs['street']
        street_number = attrs['street_number']
        apartment_number = attrs['apartment_number'] if 'apartment_number' in attrs else None
        unique = check_address_unique(city, street, street_number, apartment_number)
        if not unique:
            raise serializers.ValidationError(_('Another user has already been registered under this address.'))
        return attrs

问题是传递错误的字段名称是此标准non_field_errors

{"non_field_errors":["Another user has already been registered under this address."]}

我想以某种方式给这个错误一个自定义名称,所以所需的输出将是:

{"address":["Another user has already been registered under this address."]}

如何做到这一点?

2 个答案:

答案 0 :(得分:4)

对于单个ValidationError,您可以这样做:

raise serializers.ValidationError({
    'address': _('Another user has already been registered under this address.')
})

如果要全局覆盖此名称,可以使用NON_FIELD_ERRORS_KEY REST框架设置。

答案 1 :(得分:1)

有用的可能是this

在这里,您可以找到自定义ValidationError输出所需的全部内容。

例如:

raise ValidationError(
   _('Invalid value: %(value)s'),
   code='invalid',
   params={'value': '42'},
)