错误消息中的Django DRF显示字段的verbose_name

时间:2019-03-25 22:30:14

标签: django django-rest-framework

当模型字段验证失败时,我希望DRF在错误消息中返回字段verbose_name。

示例:

models.py:

class MyClass(models.Model):
    myfield = model.CharField(max_length=20,\
                              verbose_name="This is the field",\
                              default="blabla")

serialiers.py:

class MyClassSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyClass
        fields = ('myfield',)

如果该字段的POSTED数据超过20个字符,则响应有效载荷为:

{"myfield":["the error message..........."]}

要向用户发送更友好的消息(...并轻松管理错误:-)),我想使用模型字段的verbose_name,因此响应有效载荷应为:

{"This is the field":["the error message..........."]}

你有什么主意吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

我认为没有简单的方法可以做到这一点。最简单的方法是覆盖序列化程序的errors属性,并使用详细名称更改错误密钥。

class TestSerializer(serializers.ModelSerializer):
    class Meta:
        model = ...
        fields = ('field1', ...)

    @property
    def errors(self):
        # get errors
        errors = super().errors
        verbose_errors = {}

        # fields = { field.name: field.verbose_name } for each field in model
        fields = {field.name: field.verbose_name for field in
                   self.Meta.model._meta.get_fields() if hasattr(field, 'verbose_name')}

        # iterate over errors and replace error key with verbose name if exists
        for field_name, error in errors.items():
            if field_name in fields:
                verbose_errors[str(fields[field_name])] = error
            else:
                verbose_errors[field_name] = error
        return verbose_errors