身份验证错误,密码错误

时间:2018-12-13 10:27:37

标签: django django-forms

我正在处理一个类似于用户登录表单的表单,但是没有默认的django的默认授权。因此它需要参数并检查输入的密码是否正确。

def clean(self):
    form_data=self.cleaned_data
    LoginUsername=form_data['Username']
    LoginPassword=form_data['Password']
    if DiaryUser.objects.filter(Username=LoginUsername):
        UserCredentials=DiaryUser.objects.filter(Username='LoginUsername')
        for UserCredential in UserCredentials:
            if UserCredential.Password !=LoginPassword:
                raise ValidationError("The Password is not correct ")
    else:
        self._errors["Username"]="The User Credentials entered is not present in our database"
        del form_data['Username']
    return form_data

但是,当用户输入错误密码时,它将继续重定向到成功页面。上面的代码段有什么问题。

2 个答案:

答案 0 :(得分:0)

使用exists更新这样的代码:

if not DiaryUser.objects.filter(Username=LoginUsername, Password=LoginPassword).exists():  # FYI Keeping plain passwords in DB is not safe and ofcourse not recommended.
     raise ValidationError("The Password is not correct ")

答案 1 :(得分:0)

感谢@ruddra,但它使我的页面相当多,但以下代码段对我有用

    form_data=self.cleaned_data
    LoginUsername=form_data['Username']
    LoginPassword=form_data['Password']
    if DiaryUser.objects.filter(Username=LoginUsername,Password=LoginPassword).exists():
        pass
    else:
        self._errors["Username"]="The User Credentials entered is not present in our database"
        return form_data

再次感谢ruddra