I am trying to create an auth backend to allow my users to log in using either their email address or their username in Django 1.6 with a custom user model. The backend work
I implemented the solution in my view. However, my users are not allowed to have emails as username during registration and also each email is unique.
if request.method=="POST":
username = request.POST.get('username').lower()
password = request.POST.get('password')
'''check if the username is a valid email'''
try:
email = validate_email(username)
username = User.objects.get(email=username).username
except:
pass
user = authenticate(request, username=username, password=password)
if user is not None:
login(request,user)
else:
messages.error(request,("Error logging in."))
return redirect('login')
I am using validate_email so that my users can have @ in their usernames, @bestuser is a valid username but not a valid email. It works for me and I don't have to overwrite the authenticate method.