[英]django authenticate not working
我正在使用遗留数据库,其中有一个表'tbl_personaldetails',从我将数据移植到用户模型。 在从tbl_personaldetails端口数据的代码中,我使用user.set_password(password)
将password设置为用户表中的hash。 麻烦的是当我尝试进行身份验证(用户名=用户名,密码=密码),其中密码和用户名是纯文本,身份验证返回无(即使对于我可以在管理部分登录的超级用户帐户)。
登录的代码如下:
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.它呈现没有任何错误消息的表单
。
我做错了什么,一切看起来都不错
据我所知,从代码片段中,您使用的是电子邮件作为用户名。 使用电子邮件地址,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/ 。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.