I receive an error when I try to login to an account on my website

I cannot login to any account, because I receive an error:

Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive.(for an admin user)

And

Please enter a correct email and password. Note that both fields may be case-sensitive.

That happens after I update a profile through the profile-detail page. It just throws me to the login page after I press the Update button on the profile-update page.

Here is all the related code:

models.py

  
class Customer(AbstractUser):
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']
    
    objects = UserManager()
    
    customer_id = models.AutoField(primary_key=True)
    first_name = models.CharField(max_length=50, null=True, blank=True)
    last_name = models.CharField(max_length=50, null=True, blank=True)
    username = models.CharField(max_length=30, null=True, blank=True)
    phone = models.CharField(max_length=10, default='', null=True,  blank=True)
    email = models.EmailField(validators=[validators.EmailValidator()], unique=True)
    description  = models.TextField(max_length=1000,blank=True, null=True)
    gender = models.CharField('Gender', max_length=10, choices=Gender.choices,
                                default='Male', null=True)
    
    featured_img = models.ImageField(verbose_name='A profile image',
                                     upload_to='profiles', 
                                     default='products/profile_default.jpg')
    
    password = models.CharField(max_length=100, null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        return f'{self.email} {self.username} {self.customer_id}'
    
    @staticmethod
    def get_customer_by_email(email):
        try:
            return Customer.objects.get(email=email)
        except:
            return False

    def exists(self):
        if Customer.objects.filter(email=self.email):
            return True

        return False

    class Meta:
        verbose_name = 'Customer'
        verbose_name_plural = 'Customers'
        # unique_together = ['email']


class Profile(models.Model):
    # USERNAME_FIELD = 'email'
    
    profile_id = models.AutoField(primary_key=True)
   
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    updated = models.DateTimeField(auto_now=True, null=True)
    user = models.ForeignKey(Customer, on_delete=models.CASCADE,
                                    related_name="customer", null=True)
  
    class Meta:
        verbose_name = 'Profile'
        verbose_name_plural = 'Profiles'
        # unique_together = ['email']

    def __str__(self):
        return f' {self.profiled}'


        

managers.py


class UserManager(BaseUserManager):
    def create_user(self, email, first_name=None, description=None, gender=None, featured_img=None, username=None, last_name=None, phone=None, password=None):
        if not email:
            raise ValueError("User must have an email")
        if not password:
            raise ValueError("User must have a password")

        user = self.model(
            email=self.normalize_email(email),
        )
        user.first_name = first_name 
        user.username = username 
        user.last_name = last_name 
        user.password = make_password(password)  # change password to hash
        user.phone = phone 
        user.featured_img = featured_img
        user.description = description
        # user.profile = profile
        user.gender = gender
        user.admin = False
        user.staff = True
        user.active = True
        user.save(using=self._db)
        return user
        
    def create_superuser(self, email, username, password):
        if not email:
            raise ValueError("User must have an email")
        if not password:
            raise ValueError("User must have a password")

        user = self.model(
            email=self.normalize_email(email)
        )

        user.username = username 

        user.password = make_password(password)  # chang password to hash

        user.admin = True
        user.staff = True
        user.active = True
        user.save(using=self._db)
        return user

views.py


@csrf_exempt
def signup(request):
    if request.method == 'POST':
        
        form = SignUpForm(request.POST or None)
        email = request.POST['email']
        if Customer.get_customer_by_email(email=email) == False:
            if form.is_valid():
                user = form.save(commit=False)
                # account = authenticate(request, 
                #                     username=email,
                #                     password=request.POST['password'])
                
                user.username = user.username.lower()
                user.save()
                
                login(request, user, 
                    backend='allauth.account.auth_backends.AuthenticationBackend')
                
                messages.success(request, 'The account was successfully created!!!')
                return redirect(reverse_lazy('products:products'))
            
            messages.error(request, f'{form.errors}') 
            return redirect(reverse_lazy('user-auth:register'))
    
        return redirect(reverse_lazy('user-auth:login'))
    form = SignUpForm()
    context = {'form': form, 'user': request.user}
    return render(request, 'auth/register/register.html', context)



class ProfileDetailView(
                        DetailView):
    
    context_object_name = 'customer'
    template_name = 'auth/profile_detail.html'
    
    def get_object(self):
        profile = Profile.objects.filter(user__customer_id=self.kwargs['pk']).first()
        return profile.user
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['user'] = self.request.user
        return context
    
   
    

class UpdateProfileView(LoginRequiredMixin,
                        UpdateView):
    
    template_name = 'auth/profile_update.html'
    form_class = ProfileUpdateForm
    context_object_name = 'customer'
    
    def get_success_url(self):
            success_url = reverse_lazy('user-auth:profile-detail', 
                                   kwargs={'pk': self.request.user.customer_id})
            return success_url
        
    @method_decorator(ensure_csrf_cookie, name='dispatch')
    def post(self, request, *args, **kwargs):
        profile = self.get_object()
        form = ProfileUpdateForm(instance=profile)
        # if request.method == 'POST':
        form = ProfileUpdateForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            if profile:
                form.save()
            
                messages.success(request, 'Successfully updated!')
                return redirect(self.get_success_url())
            
            messages.error(request, 'Profile does not exist!')
            return redirect(reverse_lazy('user-auth:signup'))
            
        messages.error(request, 'Invalid data!')
        return render(request, self.template_name, self.get_context_data())
        
    def get_object(self):
        profile = Profile.objects.filter(user__customer_id=self.kwargs['pk']).first()
        return profile.user

    # def get(self, request, *args, **kwargs):
    #     context = {}
    #     context["form"] = ProfileUpdateForm(instance=self.get_object())
    #     context['user'] = request.user
    #     return render(request, self.template_name, context)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["form"] = ProfileUpdateForm(instance=self.get_object())
        context['user'] = self.request.user
        return context
    

class DeleteProfileView(LoginRequiredMixin, 
                        DeleteView):

        context_object_name = 'customer'
        template_name = 'auth/profile_confirm_delete.html'
        
        def get_success_url(self):
            success_url = reverse_lazy('user-auth:profile-detail', 
                                   kwargs={'pk': self.request.user.customer_id})
            return success_url
        
        def post(self, request, *args, **kwargs):
            self.request = request
            
            if self.get_object:
                messages.success(request, 'Profile deleted successfully!')
                
                return super().delete(request, *args, **kwargs)
            
            messages.success(request, 'Profile does not exist!')
            return redirect(reverse_lazy('user-auth:signup'))

        def get_object(self):
            profile = Profile.objects.filter(user__customer_id=self.kwargs['pk']).first()
            return profile.user
       

signals.py



@receiver(post_save, sender=Customer)
def create_profile(sender, instance, created, **kwargs):
    user = instance
    if created:
        print(user)
        Profile.objects.create(
           


            user=user
            
        )
        
@receiver(pre_save, sender=Customer)
def update_profile(sender, instance, **kwargs):
    # print(instance)
    profile = instance
    if profile.customer_id is not None:
     
        Profile.objects.update(user=profile)
        

@receiver(post_delete, sender=Customer)
def delete_profile(sender, instance, **kwargs):
    user = instance
    customer = Customer.objects.filter(email=user.email).first()
    if user and customer:
        # profile.delete()
        customer.delete()
    print('Not exists...')
    

forms.py


class SignUpForm(UserCreationForm):

    class Meta:
        model = Customer
        fields = ('username','phone', 'first_name', 'last_name', 'email', 'featured_img') 
        
        # def __init__(self, *args, **kwargs):
        #     super(SignUpForm, self).__init__(*args, **kwargs)
            # for name, field in self.fields.items():
            #     field.widget.attrs.update({'class': 'input'})


  


class ProfileUpdateForm(forms.ModelForm):
    password1 = forms.CharField(
        label="Password",
        strip=False,
        widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
        help_text=password_validation.password_validators_help_text_html(),
        required=False
    )
    password2 = forms.CharField(
        label="Password confirmation",
        widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
        strip=False,
        help_text="Enter the same password as before, for verification.",
        required=False
    )
    class Meta:
        model = Customer
        fields = ('username', 'phone', 'first_name', 'last_name', 'email', 'featured_img', 'description', 'gender')
        
    def save(self, commit=True):
        customer = super().save(commit=False)
        
        email = self.cleaned_data.get('email')
        customer.email = email.lower()
        # customer.password = customer.set_password(self.cleaned_data['password1'])
        
        if commit:
            if customer.exists():
                super(ProfileUpdateForm, self).save()
                return customer
            
            

urls.py


from django.contrib.auth import views as auth_views

app_name = 'user-auth'

urlpatterns = [

    path('register/', views.signup, name='register'),
    path('accounts/login/', auth_views.LoginView.as_view(
                            template_name='auth/login/login.html',
                            success_url='products/'),
                            name='login'
                            ),
    path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'),
    path('profile-detail/<int:pk>/', views.ProfileDetailView.as_view(), name='profile-detail'),
    path('profile-update/<int:pk>/', views.UpdateProfileView.as_view(),
                                            name='profile-update'),
    path('profile-delete/<int:pk>/', views.DeleteProfileView.as_view(),
                                            name='profile-delete'),
    
    
    
] 


I have tried to delete my database and fill it in once again. Then I tried to find out why the email or password dis incorrect. Maybe they are wrong in the database. But I have no idea what's going on.

Back to Top