【问题标题】:Change errors in password change serializer in rest-authrest-auth 中密码更改序列化程序中的更改错误
【发布时间】: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


    【解决方案1】:

    您可以使用serializers.CharFielderror_messages 属性。

    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
    

    【讨论】:

    • 这可行,但是,我收到此错误:'PasswordChangeSerializer' object has no attribute 'old_password_field_enabled' 我知道我必须实现这个,但是在我实现所有内容之后,当我需要确认时,我没有收到正确的错误消息密码。例如,假设我输入的新密码与确认时的密码不同。它不是说密码不匹配,而是说此字段不能为空。
    • @user2896120 PasswordChange 类应该继承自 PasswordChangeSerializer。我已经在我的回答中纠正了这一点。你能再检查一下吗?
    • 是的,这非常有效,但是,如果提供的凭据不正确,响应为 400 bad request 错误是否正常?
    • @user2896120 我认为是的。从文档中这些异常由 REST 框架提供的默认异常处理程序自动处理,并且默认返回 HTTP 400 Bad Request 响应。。更多详情请见this link
    • @user2896120 另见source code。 DRF 默认使用status_code = status.HTTP_400_BAD_REQUEST,同时提升serializers.ValidationErrors。
    猜你喜欢
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多