from django import forms
from django.contrib.auth.forms import AuthenticationForm

class CustomAuthenticationForm(AuthenticationForm):
       username = forms.CharField(label='Username or Email', max_length=250,widget=forms.TextInput(attrs={'placeholder':'Usuario ou Email','class':'form-control form-control-lg bg-light fs-6'}))
       password = forms.CharField(label='Senha', max_length=250,widget=forms.PasswordInput(attrs={'placeholder':'Senha','class':'form-control form-control-lg bg-light fs-6'}))

       def clean(self):
           username = self.cleaned_data.get('username')
           password = self.cleaned_data.get('password')

           if '@' in username:
               # Consider the input as an email
               from django.contrib.auth.models import User
               try:
                   user = User.objects.get(email=username)
                   self.cleaned_data['username'] = user.username
               except User.DoesNotExist:
                   raise forms.ValidationError("User with this email does not exist.")
           return super().clean()
