Django身份验证不起作用

2024-09-29 02:20:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是一个遗留数据库,其中有一个表“tbl\u personaldetails”,从中我将数据移植到定制用户模型。 在从tbl\u personaldetails导入数据的代码中,我使用了user.set_password(password),它在用户表中将密码设置为散列。 问题是当我尝试验证(username=username,password=password)时,password和username都是纯文本,authenticate返回None(甚至对于可以在管理部分登录的超级用户帐户)。在

登录代码如下:

class LoginView(FormView):
    form_class = LoginForm
    template_name = 'account/login.html'

    def get_success_url(self):
        return reverse("userHomeAfterLogin")

    def form_valid(self, form):
        email = form.cleaned_data['email'].lower().strip()
        password = form.cleaned_data['password']
        user = authenticate(email=email, password=password)
        if user:
            login(self.request, user)
            return redirect(self.get_success_url())
        else:
            try:
                user = User.objects.get(email__iexact=email)
                if not check_password(password, user.password):
                    form._errors['password'] = ErrorList([u'That is not the correct Password.'])
            except User.DoesNotExist:
                form._errors['email'] = ErrorList([u'This email is not registered with us.'])
            context = self.get_context_data(form=form)
            return self.render_to_response(context)

现在它是这样流动的: 1.authenticate返回none,在else部分登录: 2可以通过电子邮件检索用户并检查密码是否正确。 三。它呈现表单,不显示任何错误消息

一。在

我做错什么了,一切看起来都很好


Tags: 用户selfformdatagetreturnemailcontext
1条回答
网友
1楼 · 发布于 2024-09-29 02:20:25

据我从代码片段中了解,您使用的是电子邮件作为用户名。Django的电子邮件地址永远无法验证。它需要用户名。参见下面的代码。在

def authenticate(**credentials):
"""
If the given credentials are valid, return a User object.
"""
for backend in get_backends():
    try:
        user = backend.authenticate(**credentials)
    except TypeError:
        # This backend doesn't accept these credentials as arguments. Try the next one.
        continue
    if user is None:
        continue
    # Annotate the user object with the path of the backend.
    user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
    return user

要使用电子邮件地址作为用户名字段,请参考http://justcramer.com/2008/08/23/logging-in-with-email-addresses-in-django/。在

希望这有帮助。在

相关问题 更多 >