【发布时间】:2015-12-02 00:49:43
【问题描述】:
我正在使用 DRF 3.2.3 并遇到了这个问题。我有这个用于创建用户的序列化程序(网络应用使用自定义用户模型):
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
问题是,模型中指定的错误消息被完全忽略。例如,GRUser 模型中的 email 字段是这样定义的:
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."),
})
使用可浏览的 api 时,DRF 甚至设法从模型中获取并显示帮助文本,但是,当我输入已使用的电子邮件而不是 "A user with that email already exists" 时,我会收到 DRF 的默认 "This field must be unique." 消息。
发生这种情况是否有设计原因?我能否以某种方式让 DRF 使用模型中的错误消息(除了违反 DRY 原则并在序列化程序中手动重复其文本的明显解决方案)?
【问题讨论】:
标签: django python-3.x django-rest-framework