django认证不起作用

时间:2013-11-19 07:17:17

标签: python django authentication

我正在使用遗留数据库,其中有一个表'tbl_personaldetails',从我将数据移植到用户模型。 在从tbl_personaldetails端口数据的代码中,我使用user.set_password(password)将密码设置为用户表中的哈希。 麻烦的是当我尝试进行身份验证时(username = username,password = password),其中password和username是纯文本,authenticate返回None(即使是超级用户帐户,我可以从admin部分登录)。

登录的代码如下:

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,登陆其他部分:     2.可以通过电子邮件检索用户并且check_password是正确的。     3.它呈现没有任何错误消息的表单

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

1 个答案:

答案 0 :(得分:3)

据我所知,从代码段中可以看出,您使用的是电子邮件作为用户名。使用电子邮件地址,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/

希望这有帮助。

相关问题