自定义ModelSerializer错误消息被忽略 [英] Customizing ModelSerializer error message is being ignored

查看:66
本文介绍了自定义ModelSerializer错误消息被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的UserSerializer(我使用的是默认的Django用户模型):

This is my UserSerializer (I'm using the default Django User model):

class UserSerializer(SetCustomErrorMessagesMixin, serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
            super(UserSerializer, 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
                self.fields[field].error_messages['null'] = 'Enter a valid %s.'%field

                # class CharField(Field) errors
                self.fields[field].error_messages['blank'] = 'Enter a valid %s.'%field
                self.fields[field].error_messages['max_length'] = '%s cannot have more than {max_length} characters.'%field
                self.fields[field].error_messages['min_length'] = '%s cannot have less than {min_length} characters.'%field

    class Meta:
        model = User
        fields = ('username', 'password', 'email',)

问题是,当用户输入的用户名过长时,错误消息为

The problem is, when a user inputs a username which is too long, the error message is

"Username is too long."

此错误消息来自何处?我改写了上面代码中的"max_length"错误消息,但没有显示出来.当我从UserSerialzer删除此行时:

Where is this error message coming from? I overwrote the "max_length" error message in the code above, but it does not show it. When I delete this line from my UserSerialzer:

self.fields[field].error_messages['max_length'] = '%s cannot have more than {max_length} characters.'%field

然后错误消息是:

"Ensure this field has no more than 30 characters."

这是有道理的,因为它来自CharField DRF源代码: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/fields.py

which makes sense beause it is coming from the CharField DRF source code here: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/fields.py

但是用户名太长"在哪里.来源和来源,并没有说用户名不能超过{max_length}个字符."代替?

But where is "Username is too long." coming from and how come it does not say "Username cannot have more than {max_length} characters." instead?

推荐答案

问题似乎是DRF在构造字段时为字段添加了验证器,并复制了字段类中的错误消息.

The problem appears to be that DRF adds validators for fields during their construction and copies the error messages from field classes.

例如,来自 rest_framework.fields.CharField .__ init __ :

if self.min_length is not None:
    message = self.error_messages['min_length'].format(min_length=self.min_length)
    self.validators.append(MinLengthValidator(self.min_length, message=message))

因此,当您覆盖消息时,它们已经在验证程序中使用.

So at the moment you are overwriting the messages, they are already used in the validators.

我认为您可以创建一个 yourapp.fields 模块,在其中子类化DRF序列化器字段并覆盖它们的 default_error_messages ,如下所示:

I think you can just create a yourapp.fields module where you subclass DRF serializer fields and override their default_error_messages, like so:

from rest_framework import fields

class CharField(fields.CharField):

    default_error_messages = {
        # Your messages
    }

然后只需切换导入字段的模块即可.

And then just switch the module you import fields from.

您可能还想覆盖 __ init __ 来在消息中添加字段名称.

You might also want to override __init__s to add field names in messages.

这篇关于自定义ModelSerializer错误消息被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆