我正在使用Django rest-auth进行注册,更改密码等端点。我正在使用包含旧密码,新密码和确认密码的密码更改端点。我试图覆盖原始序列化程序中的某些内容,例如,如果该字段不正确,则添加我自己的错误消息。但是,我很难覆盖的一条错误消息是这些字段是否为空白。每次都会显示默认错误消息,如下所示:
{
"old_password": [
"This field may not be blank."
],
"new_password1": [
"This field may not be blank."
],
"new_password2": [
"This field may not be blank."
]
}
如果该字段为空白,我想实现自己的错误消息,但是,我无法执行此操作。这是我创建的序列化器:
class PasswordChange(PasswordChangeSerializer):
set_password_form_class = SetPasswordForm
def validate_old_password(self, value):
invalid_password_conditions = (
self.old_password_field_enabled,
self.user,
not self.user.check_password(value)
)
if all(invalid_password_conditions):
raise serializers.ValidationError('The password you entered is invalid.')
return value
这是表单类:
class PasswordForm(ChangePasswordForm):
oldpassword = PasswordField(label=_("Current Password"))
password1 = SetPasswordField(label=_("New Password"))
password2 = PasswordField(label=_("Confirm New Password"))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['oldpassword'].widget = forms.PasswordInput(attrs={"placeholder": ""})
self.fields['password1'].widget = forms.PasswordInput(attrs={"placeholder": ""})
self.fields['password2'].widget = forms.PasswordInput(attrs={"placeholder": ""})
def clean_oldpassword(self):
if not self.user.check_password(self.cleaned_data.get("oldpassword")):
raise forms.ValidationError(_("The password you entered is invalid."))
我这样做正确吗?字段为空白时,如何更改显示的错误消息?
答案 0 :(得分:1)
您可以使用serializers.CharField
的{{3}}属性。
class PasswordChange(PasswordChangeSerializer):
my_default_errors =
{
'blank': 'your_message',
'required': 'your_message',
}
old_password = serializers.CharField(max_length=128, error_messages=my_default_errors)
new_password1 = serializers.CharField(max_length=128, error_messages=my_default_errors)
new_password2 = serializers.CharField(max_length=128, error_messages=my_default_errors)
def validate_old_password(self, value):
invalid_password_conditions = (
self.old_password_field_enabled,
self.user,
not self.user.check_password(value)
)
if all(invalid_password_conditions):
raise serializers.ValidationError('The password you entered is invalid.')
return value