Check if user exist and password is not correct django

Question:

I am trying to return an error message Password is not correct if user enters an invalid password on login form. My problem however is that I cannot check user exist and password is incorrect.

Here is my views.py for signin

def signin(request):
    if request.user.is_authenticated:
        return redirect(index)
    if request.method == "POST":
        form = Signin(request.POST)
        if form.is_valid():
            username = request.POST["username"]
            password = request.POST["password"]

            # try:

            user = auth.authenticate(username=username, password=password)

            if user is not None:
                auth.login(request, user)
                return redirect(index)

            elif user is None:
                messages.error(request, "User does not exist")
                return redirect(signin)
    else:
        form = Signin()
        return render(
            request,
            "accounts/login.html",
            {
                "form": form,
            },
        )

As you can see, I can check if user exist or not. What I want to do is check if user exist and password is incorrect, return error message.

Asked By: Olasubomi

||

Answers:

you can write code like this…

from django.contrib.auth.hashers import check_password
def SigninView(request):
    if request.method == 'POST':
        uname = request.POST['uname']
        upass = request.POST['upass']
        get_user_obj=User.objects.filter(username=uname).exists()
        if get_user_obj:
            get_user=User.objects.filter(username=uname)
            check_pass = check_password(upass,get_user[0].password)
            if not check_pass:
                print(f"Password dose not exist with username = {get_user[0].username}")
                return redirect('/')
            else:
                login(request,get_user[0])
                print('Login Success')
                return redirect('/shop/')
        else:
            print('Username dose not exist')
            return redirect('/')
    return render(request,'signin.html')