So I’m starting to learn Django authentication.
from django.contrib.auth import login as log_in
def login(request):
...
if request.method == "POST":
form = UserLoginForm(request.POST)
if form.is_valid():
user = User.objects.filter(email=form.cleaned_data["email"])
if user.exists():
user = user.first()
if check_password(
form.cleaned_data["password"], user.password
):
log_in(request,user)
return redirect("/main/")
else:
messages.warning(request, "email/password are incorrect")
else:
messages.warning(request, "User not found")
...
and I’m trying to access the request.user in another view like this:
if request.user.is_authenticated:
#do somthing
but while debugging I found that after the first code log_in() statement the request.user is authenticated, but in the seconed code it’s not.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You have to set the authentication backend:
from django.conf import settings
# ...
user.backend = settings.AUTHENTICATION_BACKENDS[0]
log_in(request, user)
Method 2
I found the problem,
The problem is that I’m using a custom user model with an email attribute instead of a username so I had to build a new Backend to use with my custom model, then added it to the AUTHENTICATION_BACKENDS in the settings.py file.
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import check_password
from .models import User
class NewBackend(ModelBackend):
def authenticate(self, request, email, password) -> User:
try:
user: User = User.objects.get(email=email)
if user.check_password(password):
return user
else:
return None
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
and in views.py
def login(request: HttpRequest):
if request.user.is_authenticated:
return redirect("/main/")
if request.method == "POST":
form = UserLoginForm(request.POST)
if form.is_valid():
umail=form.cleaned_data['email']
upasswd=form.cleaned_data['password']
user = authenticate(request=request,email=umail,password=upasswd)
if user is not None:
log_in(request,user)
return redirect("/main/")
else:
messages.warning(request, "email/password are incorrect")
form = UserLoginForm()
context = {"title": "Login", "form": form}
return render(request, "login.html", context)
settings.py:
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'login_signup.backend.NewBackend',
]
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0