Django, How to Login with Username and email

sometimes error with my code, I am trying to use try and expect but can't work. I want to make login with username and email Please helping to solve problems.

View.py

def login_attempt(request):
    if request.method == 'POST' :
       username = request.POST.get('username')
        email    = request.POST.get('username')
        password = request.POST.get('password')
       try: 
              user_obj = User.objects.filter(email = email.lower()).first()    
        except: 
              user_obj = User.objects.filter(username = username.lower()).first()
        try: 
            user = authenticate(username = username.lower(), password = password )
        except:
            user = authenticate(email = email.lower(), password = password 
       login(request, user);
       return render(request, 'login.html',context)

from django.contrib.auth import authenticate, login
def login_view(request, *args, **kwargs):
    user=request.user
    form=LoginForm(request.POST)
    if request.POST:
        if form.is_valid():
            email=request.POST['email']
            password=request.POST['password']
            user=authenticate(email=email, password=password)
            if user:
                login(request, user)
                return redirect('products-home')
    else:
        form=LoginForm() 
    return render(request, 'customUser/login.html',{'form':form})

If you want to login user with email or username. You might need to use try/except to handle errors. And don't forget that there are more strong ways to detect emails. here is the snippet:

def login_attempt(request):
    if request.method == 'POST' :
        login_input = request.POST.get('username').lower()
        password = request.POST.get('password')

        """
        alternative: 
             if ".com" in login_input
        """
        if "@" in login_input:
            user_obj = User.objects.filter(email = login_input)).first()
            user = authenticate(email = user_obj.email, password = password )
        else:
            user_obj = User.objects.filter(username = login_input).first()
            user = authenticate(email = user_obj.username, , password = password 
       login(request, user);
       return render(request, 'login.html',context)

NOTE: I assume that you already have a custom authentication model to log users with email

Back to Top