Always incorrect password in Django

34 Views Asked by At

So, the problem is always incorrect password even though its correct. I make sure to type the password correctly in the register and yet in the login its incorrect password. I don't know how to fix it anymore, I'm lost.

views.py
from django.contrib.auth.hashers import make_password, check_password
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import authenticate, login
from .forms import RegistrationForm, LoginForm
from django.shortcuts import render, redirect
from django.contrib import messages
from django.shortcuts import HttpResponse
from .models import *

# Create your views here.
def home(request):
    return render (request,"home.html")

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email').strip()  # Trim leading and trailing whitespace
            password = form.cleaned_data.get('password1').strip()  # Trim leading and trailing whitespace
            if Customer.objects.filter(email=email).exists():
                messages.error(request, "A customer with this email already exists.")
                return redirect('user_register')
            # Hash the password using make_password
            encrypted_password = make_password(password)
            customer = Customer.objects.create(
                username=form.cleaned_data['username'],
                firstname=form.cleaned_data['firstname'],
                lastname=form.cleaned_data['lastname'],
                email=email,
                address=form.cleaned_data['address'],
                phone=form.cleaned_data['phone'],
                birthdate=form.cleaned_data['birthdate'],
                password1=encrypted_password
            )
            messages.success(request, "You registered successfully!")
            return redirect('login')
    else:
        form = RegistrationForm()
    return render(request, "register.html", {'form': form})

def user_login(request):
    if request.method == 'POST':
        email = request.POST.get('email').strip()  # Trim leading and trailing whitespace
        password = request.POST.get('password').strip()  # Trim leading and trailing whitespace
        try:
            user = Customer.objects.get(email=email)
            stored_password = user.password1.strip()  # Trim leading and trailing whitespace from stored password

            # Debugging: Print or log variable values
            print("Email:", email)
            print("Password:", password)
            print("Stored Password:", stored_password)

            # Check if the provided password matches the stored hashed password
            if check_password(password, stored_password):
                # Authenticate the user
                authenticated_user = authenticate(request, email=email, password=password)
                if authenticated_user is not None:
                    # Log in the authenticated user
                    login(request, authenticated_user)
                    messages.success(request, "Login successfully!")
                    return redirect('home')
                else:
                    # Incorrect password
                    messages.error(request, "Incorrect password. Please try again. #1")
                    return redirect('login')
            else:
                # Incorrect password
                messages.error(request, "Incorrect password. Please try again. #2")
                return redirect('login')
        except Customer.DoesNotExist:
            # Incorrect email
            messages.error(request, "Incorrect email. Please try again.")
            return redirect('login')
    else:
        form = LoginForm()
        return render(request, "login.html", {'form': form})

Below is my models that I will use.

models.py


from django.db import models
from django.core.validators import MinValueValidator
    
class Customer(models.Model):
    username = models.CharField(max_length=200, null=True)
    firstname = models.CharField(max_length=200, null=True)
    lastname = models.CharField(max_length=200, null=True)
    email = models.EmailField(max_length=200, null=True)
    address = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=11, null=True)
    birthdate = models.DateField(null=True)
    password1 = models.CharField(max_length=256, null=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
        
    def __str__(self):
        return  f"({self.firstname} {self.lastname} {self.email})"
    
class Menu(models.Model):
    name = models.CharField(max_length=200, null=True)
    price = models.DecimalField(max_digits=10, decimal_places=2,null=True)    
    
    def __str__(self):
        return self.name

This is my forms.py

forms.py
from django import forms
from .models import Customer
from django.contrib.auth.hashers import make_password

class RegistrationForm(forms.ModelForm):
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)

    class Meta:
        model = Customer
        fields = ['username', 'firstname', 'lastname', 'email', 'address', 'phone', 'birthdate', 'password1', 'password2']
                
    def clean_email(self):
        email = self.cleaned_data['email']
        if Customer.objects.filter(email=email).exists():
            raise forms.ValidationError("This email address is already in use.")
        return email
    
    def clean(self):
        cleaned_data = super().clean()
        password1 = cleaned_data.get("password1")
        password2 = cleaned_data.get("password2")
        if password1 != password2:
            raise forms.ValidationError("Passwords do not match.")
        return cleaned_data
    
    def save(self, commit=True):
        user = super().save(commit=False)
        user.password1 = make_password(self.cleaned_data['password1'])
        if commit:
            user.save()
        return user
    
class LoginForm(forms.Form):
    email = forms.EmailField(max_length=200)
    password1 = forms.CharField(label='Password1', widget=forms.PasswordInput)

That is all the code I have.

0

There are 0 best solutions below