AttributeError:“ NoneType”对象没有属性“ check_password”

时间:2020-09-18 09:18:15

标签: django

我看到这个问题已经被问过很多遍了,但是对我来说却没有用。问题是authenticate方法始终返回None。

这就是我在设置中添加的内容

# Custom User
AUTH_USER_MODEL = 'account.CustomUser'

#Authentication backends
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
)

这是表单类中的clean方法

class LoginForm(forms.Form):
    email = forms.EmailField(widget=forms.EmailInput(attrs=email_attr))
    password = forms.CharField(widget=forms.PasswordInput(attrs=password1_attr))
    
    class Meta:
        fields = ['email', 'password']

    def clean(self, *args, **kwargs):
        cleaned_data = super(LoginForm, self).clean(*args, **kwargs)
        email = cleaned_data.get('email')
        password = cleaned_data.get('password')
        user = authenticate(email=email, password=password)
        print(user)
        try:
            CustomUser.objects.get(email=email)
        except CustomUser.DoesNotExist:
            raise forms.ValidationError({'email': 'Email is incorrect'})

        if not user.check_password(password):
            raise forms.ValidationError({'password': 'Password is incorrect!'})
        return cleaned_data

views.py

def loginView(request):
    template_name = "app/login.html"
    form = LoginForm()
    if request.user.is_authenticated:
        return redirect('home')
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            email = request.POST['email']
            password = request.POST['password']
            user = authenticate(email=email, password=password)
            if user is not None:
                login(request, user)
                return redirect('home')
    return render(request, template_name, {'form': form})

我遇到的错误

if not user.check_password(password):
AttributeError: 'NoneType' object has no attribute 'check_password'

1 个答案:

答案 0 :(得分:1)

authenticate已经在内部调用[1, 6, 2, 7, 3, 8, 4, 9, 5, 10] 。如果发生任何错误,该函数将返回check_password(),这似乎是您遇到错误的情况。

如果问题是电子邮件不存在或密码错误,也建议不要在错误消息中公开。它称为user enumeration,尽管它本身并不是漏洞,但它可以为潜在的攻击者提供有关您的用户帐户的信息。