Django rest框架忽略了在模型上设置的error_messages

时间:2021-05-15 19:18:30

I'm using DRF 3.2.3 and running into this problem. I have this serializer that's used to create users (web app uses a custom user model):

我正在使用DRF 3.2.3并遇到此问题。我有这个用于创建用户的序列化程序(Web应用程序使用自定义用户模型):

class CreateGRUserSerializer(serializers.ModelSerializer):
    confirm_password = serializers.CharField(max_length=128, allow_blank=False, 
            write_only=True, style={'input_type': 'password'})

    def validate(self, data):
        if data['password'] != data['confirm_password']:
            raise serializers.ValidationError({'password': "Passwords do not match", 'confirm_password': "Passwords do not match"})
        return data

    class Meta:
        model = GRUser
        fields = ('username', 'email', 'password', 'confirm_password')
        extra_kwargs = {'password': {'write_only': True, 'style': {'input_type': 'password'}}}

    def create(self, validated_data):
        user = GRUser(
            email=validated_data['email'],
            username=validated_data['username']
        )
        user.set_password(validated_data['password'])
        user.init_activation(False)
        user.save()
        return user

Problem is, error messages that were specified in model are completely ignored. For example, email field is defined like this in the GRUser model:

问题是,完全忽略模型中指定的错误消息。例如,电子邮件字段在GRUser模型中定义如下:

email = models.EmailField(_('email address'), unique=True,
    help_text=_('Email address that acts as the primary unique identifier for the user.'),
    error_messages={
        'unique': _("A user with that email already exists."),
    })

When using browsable api, DRF even manages to get and display the help text from the model, however, when I input an already used email, instead of "A user with that email already exists", I get DRF's default "This field must be unique." message.

当使用可浏览的api时,DRF甚至设法从模型中获取并显示帮助文本,但是,当我输入已使用的电子邮件时,而不是“已存在该电子邮件的用户”,我得到DRF的默认值“此字段必须是独特。”信息。

Is there a design reason why it happens? Can I somehow make DRF use error messages from the model (other than the obvious solution of violating the DRY principle and repeating their text manually in the serializer)?

是否有设计原因发生?我可以以某种方式使DRF使用模型中的错误消息(除了违反DRY原则的明显解决方案并在序列化器中手动重复其文本)?

2 个解决方案

#1


1  

You may have to override the UniqueValidator that is already used by ModelSerializer for unique fields. The default validator, doesn't uses messages from model, as of now. This is how you would do it:

您可能必须覆盖ModelSerializer已用于唯一字段的UniqueValidator。默认验证程序不使用来自模型的消息,截至目前。这是你怎么做的:

class CreateGRUserSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(validators=[
            UniqueValidator(
                queryset=GRUser.objects.all(),
                message="A user with that email already exists.",
            )]
        )

Or you can update the 'unique' key of 'error_messages' property of fields['email'] in serializer's __init__() method.

或者,您可以在序列化程序的__init __()方法中更新字段['email']的'error_messages'属性的“唯一”键。

#2


0  

This functionality has now been added to DRF. See https://github.com/tomchristie/django-rest-framework/issues/2878.

此功能现已添加到DRF中。请参阅https://github.com/tomchristie/django-rest-framework/issues/2878。

#1


1  

You may have to override the UniqueValidator that is already used by ModelSerializer for unique fields. The default validator, doesn't uses messages from model, as of now. This is how you would do it:

您可能必须覆盖ModelSerializer已用于唯一字段的UniqueValidator。默认验证程序不使用来自模型的消息,截至目前。这是你怎么做的:

class CreateGRUserSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(validators=[
            UniqueValidator(
                queryset=GRUser.objects.all(),
                message="A user with that email already exists.",
            )]
        )

Or you can update the 'unique' key of 'error_messages' property of fields['email'] in serializer's __init__() method.

或者,您可以在序列化程序的__init __()方法中更新字段['email']的'error_messages'属性的“唯一”键。

#2


0  

This functionality has now been added to DRF. See https://github.com/tomchristie/django-rest-framework/issues/2878.

此功能现已添加到DRF中。请参阅https://github.com/tomchristie/django-rest-framework/issues/2878。