如何修复表单密码验证,密码没有匹配

时间:2017-06-25 17:19:05

标签: django django-forms django-views

当我输入我的用户名和密码时,这个错误就会爆炸,他说用户名和密码不匹配,但所有数据都是真实的!怎么解决? 如果数据库中的密码以加密形式存储,以及提供的密码以字符串形式存储,如何检查密码!

谢谢大家的帮助,我期待着您的建议!

forms.py

class UserLogInForm(forms.Form):
    username = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Username"), error_messages={ 'invalid': _("This value must contain only letters, numbers and underscores.") })
    password = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password"))

def clean_username(self):
    user = User.objects.get(username__iexact=self.cleaned_data['username'])
    if user: 
        return self.cleaned_data['username']
    else:
        raise forms.ValidationError('This user does not exist!')

def clean(self):
    username = self.cleaned_data['username']
    password = self.cleaned_data['password']
    user = User.objects.filter(username=username)
    if user.count() == 1:
        user = user.first()
        if user.check_password(password):
            raise forms.ValidationError("Incorrect password!")
        return self.cleaned_data
    else:
        raise forms.ValidationError('This user does not exist!')

views.py

def login_view(request):
    form = UserLogInForm(request.POST or None)
    if form.is_valid():
        username = form.cleaned_data['username'],
        password = form.cleaned_data['password'],

        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('/')
        else:
           return redirect('accounts/login')
    context = {'form':form}
    return render(request, 'accounts/registration/login.html', context)

1 个答案:

答案 0 :(得分:1)

check_password()返回True时,您将引发错误。

我建议您重新编写类似的方法,

def clean(self, *args, **kwargs):
    username = self.cleaned_data.get("username")
    password = self.cleaned_data.get("password")
    try:            
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        raise forms.ValidationError("This user does not exist!")  
    if user and not user.check_password(password):
        raise forms.ValidationError("Incorrect password!"):
    if user and not user.is_active:
        raise forms.ValidationError("This user is no longer active.")
    return super(UserLogInForm, self).clean(*args, **kwargs)

此外,从视图中的这些行中删除尾随逗号

username = form.cleaned_data['username']
password = form.cleaned_data['password']

由于尾​​随逗号,python返回一个元组而不是字符串。