In my project, I implement a login system where a user can login using their username or their email. I basically try to find whether a users email is inserted into the form field "usernameOrEmail" or whether it is their username entered in the "usernameOrEmail" field. I then log them in if a user is found.
Here is my code:
def login(request):
context = {}
if request.method == "POST":
isFound = ""
form = LoginForm(request.POST)
if form.is_valid():
try:
user = User.objects.get(username=form.cleaned_data.get("usernameOrEmail"))
isFound = "usernameFound"
except User.DoesNotExist:
try:
user = User.objects.get(email=form.cleaned_data.get("usernameOrEmail"))
isFound = "emailFound"
except User.DoesNotExist:
isFound = "nothingFound"
if isFound == "usernameFound":
print("USERNAME FOUND!")
user = auth.authenticate(username=form.cleaned_data.get("usernameOrEmail"), password=form.cleaned_data.get("password"))
if user is not None:
auth.login(request, user)
return redirect('home')
else:
context["error"] = "Oops, username/email or password provided is invalid"
elif isFound == "emailFound":
print("EMAIL FOUND")
user = auth.authenticate(email=form.cleaned_data.get("usernameOrEmail"), password=form.cleaned_data.get("password"))
if user is not None:
print("YES")
auth.login(request, user)
return redirect('home')
else:
print("NO")
context["error"] = "Oops, username/email or password provided is invalid"
else:
context["error"] = "Oops, username/email or password provided is invalid"
else:
context["error"] = "Please enter valid form data"
else:
form = LoginForm()
Weirdly, the terminal return the print statement "EMAIL FOUND" meaning that the email of a user was found, however the "NO" print statement is also printed, and the message "Oops, username/email or password provided is invalid" is returned in the template.
The other weird thing is that this system works for the users username, meaning when I enter a users username into the "usernameOrEmail" field, and I enter the correct password, the user is logged in. Anybody know the issue? thank you.
The standard authentication backend only works with a username
and password
. Indeed, the authenticate
method [GitHub] of the ModelBackend
is implemented as:
def authenticate(self, request, , password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) if username is None or password is None: return try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user
This is however not a problem. You can just implement this with:
def login(request):
context = {}
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
try:
user = User.objects.get(username=form.cleaned_data['usernameOrEmail'])
except User.DoesNotExist:
try:
user = User.objects.get(email=form.cleaned_data['usernameOrEmail'])
except User.DoesNotExist:
user = None
if user is not None:
user = auth.authenticate(username=, password=form.cleaned_data['password'])
if user is not None:
auth.login(request, user)
return redirect('home')
else:
context['error'] = 'Oops, username/email or password provided is invalid'
else:
context['error'] = 'Please enter valid form data'
else:
form = LoginForm()
# …
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.