【发布时间】:2019-06-03 22:14:16
【问题描述】:
我正在使用 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."))
我这样做正确吗?如何更改字段为空白时显示的错误消息?
【问题讨论】:
标签: python django django-rest-framework django-rest-auth