I am trying to log a user in via email in django, everything is working fine(code wise), no errors and functions execute in a right manner. However, when I perform a check in the template it always return false.
Here is my code:
authenticate_user.py
def authenticate(self, request, email=None, password=None):
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
messages.add_message(request, messages.INFO, 'Email or Password is not correct.')
print("User not found")
return None
else:
user_password_is_valid = check_password(password, user.password)
if user_password_is_valid:
print("User found")
return user
else:
messages.add_message(request, messages.INFO, 'Email or Password is not correct.')
return None
return None
And for the handle_login
view:
def handle_login(request):
context= {
'title': 'Login'
}
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
user = authenticate(request, email=email, password=password)
print('User is', user)
# This prints user no problem
if user is not None:
login(request, user)
# No errors up to this point
return redirect(reverse('mainapp:homepage'))
else:
return redirect(reverse('mainapp:homepage'))
Now upon checking -> {% user.is_authenticated %}
in the template.html
it always return false.
Upon further checking, I realized that the problem was at:
def get_user(self, email):
try:
return User.objects.get(email=email)
except User.DoesNotExist:
return None
It should be:
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
However, I am not still sure how the behavior of get_user()
work.
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.