Python django验证不工作
我使用的是一个遗留数据库,其中有一个“tbl_personaldetails”表,从中我将数据移植到custome用户模型。 在tbl_personaldetails的代码到端口数据中,我使用Python django验证不工作,python,django,authentication,Python,Django,Authentication,我使用的是一个遗留数据库,其中有一个“tbl_personaldetails”表,从中我将数据移植到custome用户模型。 在tbl_personaldetails的代码到端口数据中,我使用user.set_password(password)将密码设置为用户表中的哈希。 问题是,当我尝试验证(用户名=用户名,密码=密码)时,如果密码和用户名是纯文本的,则authenticate返回None(即使对于超级用户帐户,我也可以从超级用户帐户登录到admin部分) 要登录的代码如下所示: class
user.set_password(password)
将密码设置为用户表中的哈希。
问题是,当我尝试验证(用户名=用户名,密码=密码)时,如果密码和用户名是纯文本的,则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,登录到else部分:
2.可以通过电子邮件检索用户并检查密码是否正确。
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
要使用电子邮件地址作为用户名字段,请参阅
希望这有帮助