I have a form that only allow users to login via username . I decided to only allow user to login via email instead of username.
First, this is not a duplication of any question relating to logging via email because in my scenario, I validate and authenticate the user in forms.py
before he proceed to the final login in views so it give me the chance to raise an error for incorrect login passwords etc.
The issue i'm facing is I modified my forms.py
to raise an error if the email doesn't exist which works but It wouldn't let the user login via his email.
def LoginRequest(request):
form = LoginForm(request.POST or None)
if request.POST and form.is_valid():
user = form.login(request)
if user:
login(request, user)
return HttpResponseRedirect(reverse('Hello'))
return render(request, 'login.html',{'form': form})
This is my original code which only allow users to login via username
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(
widget=forms.PasswordInput(render_value=False)
)
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if not user or not user.is_active:
raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
return self.cleaned_data
def login(self, request):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
user = authenticate(username=username, password=password)
return user
This is my modified code which only allow users to login via email. I thought a lot about how I would do it but this is the best idea I came up with. Sorry it's a bit confusing. The problem is, it wouldn't let the user login. I don't understand why.
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(
widget=forms.PasswordInput(render_value=False)
)
def clean(self):
user = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if User.objects.filter(email=user).exists():
password = self.cleaned_data.get('password')
user = authenticate(username=user.username, password=password)
if not user or not user.is_active:
raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
return self.cleaned_data
def login(self, request):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
user = authenticate(username=username, password=password)
return user
Can someone please help me?