[英]Custom Authentication Login in Django via email
I am trying to understand login methods in Django. So because I want to login with email not username.我想了解 Django 中的登录方法。所以因为我想用 email 而不是用户名登录。 I wrote a custom authentication backend and exposed it in settings.py
我写了一个自定义身份验证后端并在 settings.py 中公开它
AUTHENTICATION_BACKENDS = (
'accounts.backend.EmailAuthenticationBackend',
'django.contrib.auth.backends.ModelBackend',
)
class EmailAuthenticationBackend(ModelBackend):
def authenticate(self, request, email=None, password=None, **kwargs):
try:
user = Account.objects.get(email=email)
if user.check_password(password):
return user
except user.DoesNotExist:
pass
And in view user_login
how I authenticate the user.并查看
user_login
我如何对用户进行身份验证。 And it's actually works.它确实有效。 I mean kind of...
我的意思是有点...
def user_login(request):
next = request.GET.get("next")
form = UserLoginForm(request.POST or None)
if form.is_valid():
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
user = authenticate(email=email, password=password)
login(request, user)
if next:
return redirect(next)
return redirect("/")
context = {
"form": form
}
return render(request, "accounts/user_login.html", context)
the authenticate()
method is returns the user. authenticate()
方法返回用户。 But redirect()
is not working because in browser thinks user not logged in. I am not sure about how to handle the session part.但是
redirect()
不起作用,因为在浏览器中认为用户未登录。我不确定如何处理 session 部分。
and custom UserLoginForm
和自定义
UserLoginForm
class UserLoginForm(forms.Form):
email = forms.CharField()
password = forms.CharField()
def clean(self, *args, **kwargs):
email = self.cleaned_data.get("email")
password = self.cleaned_data.get("password")
if email and password:
user = authenticate(email=email, password=password)
if not user:
raise forms.ValidationError("user not exist")
if not user.check_password(password):
raise forms.ValidationError("incorrect password")
return super(UserLoginForm, self).clean(*args, **kwargs)
The second issue is if email
or password
wrong.第二个问题是如果
email
或者password
错误。 it doesn't raise any error.它不会引发任何错误。
what is the best common way to handle custom login with email.使用 email 处理自定义登录的最常用方法是什么。
request.GET.get("next")
into nxt
variable, however you are checking the next
variable for redirecting, probably you should change the variable nxt
to next
.request.GET.get("next")
分配给nxt
变量,但是您正在检查next
变量以进行重定向,可能您应该将变量nxt
更改为next
。try and except
to handle the thrown errors in the authenticate()
method and you just put pass
in the excpetion
part.authenticate()
方法中放置了try and except
来处理抛出的错误,而您只是将pass
放在了excpetion
部分。 If you want the error to be thrown, just remove the try and except
part from authenticate()
.authenticate()
中删除try and except
部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.