I’d like to allow my users to be able to log in via email. I’ve seen examples of accomplishing this by writing a custom authentication back-end. I, however, would like to do this by inheriting the django.contrib.auth.forms.AuthenticationForm and adding a new field called email which on the clean_email method fetches the username from the User model and then passes it to the parent form.
I’ve tried doing this but I’ve failed miserably as I can’t seem to modify the request or populate the field value. This is what I’ve gotten so far.
class LoginForm(AuthenticationForm):
email = forms.EmailField(
required=True, label=_("Email")
)
def __init__(self, request=None, *args, **kwargs):
super(LoginForm, self).__init__(
request, *args, **kwargs
)
self.fields['username'].widget = forms.widgets.HiddenInput()
def clean_email(self):
user = User.objects.filter(email=self.cleaned_data['email'])
if user:
#self.fields['username'].value = user.username
#return user.email
else:
raise forms.ValidationError(_("Incorrect email or password."))
Thanks.
You should use
cleanif you want to modify another field:And don’t forget that email isn’t unique in Django auth.