【问题标题】:django authenticate not workingdjango身份验证不起作用
【发布时间】:2013-12-02 15:29:27
【问题描述】:

我正在使用一个遗留数据库,其中有一个表“tbl_personaldetails”,我从该表将数据移植到客户用户模型。 在从 tbl_personaldetails 移植数据的代码中,我使用 user.set_password(password) 将密码设置为用户表中的哈希值。 问题是当我尝试进行身份验证时(用户名=用户名,密码=密码),其中密码和用户名是纯文本,身份验证返回无(即使对于我可以在管理部分登录的超级用户帐户)。

登录代码如下:

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 不返回任何内容,登陆 else 部分: 2.可以用邮箱找回用户,check_password是否正确。 3. 它呈现没有任何错误消息的表单

.

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

【问题讨论】:

    标签: python django authentication


    【解决方案1】:

    据我从代码 sn-p 了解,您使用电子邮件作为您的用户名。使用电子邮件地址,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/

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-10-12
      • 2018-12-25
      • 1970-01-01
      • 2013-11-03
      • 2017-06-02
      • 1970-01-01
      • 2021-04-08
      • 2018-08-05
      • 2021-07-01
      相关资源
      最近更新 更多