更新时间:2023-09-28 13:27:34
为 dougis
指出您正在尝试使用电子邮件对用户进行身份验证,但是 authenticate
函数根据用户名和密码对用户进行身份验证。通过电子邮件(完整的工作表)对用户进行身份验证:
As dougis
pointed out you are trying to authenticate the user using email, But authenticate
function authenticates user based on username and password. So here is the trick to authenticate the user using email (complete working form):
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth import authenticate
class LoginForm(forms.Form):
email = forms.CharField()
password = forms.CharField(
widget=forms.PasswordInput(render_value=False)
)
def clean(self):
user = self.authenticate_via_email()
if not user:
raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
else:
self.user = user
return self.cleaned_data
def authenticate_user(self):
return authenticate(
username=self.user.username,
password=self.cleaned_data['password'])
def authenticate_via_email(self):
"""
Authenticate user using email.
Returns user object if authenticated else None
"""
email = self.cleaned_data['email']
if email:
try:
user = User.objects.get(email__iexact=email)
if user.check_password(self.cleaned_data['password']):
return user
except ObjectDoesNotExist:
pass
return None
views.py
def LoginRequest(request):
form = LoginForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
user = form.authenticate_user()
login(request, user)
return HttpResponseRedirect(reverse('Hello'))
return render(request, 'login.html',{'form': form})