Log in user using either email address or username in Django

后端 未结 13 2557
故里飘歌
故里飘歌 2020-12-02 08:34

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

13条回答
  •  独厮守ぢ
    2020-12-02 08:58

    You can simply have a Try block to do this.. use:

    email = request.POST['username'] 
    raw_password = request.POST['password'] 
    
       try:
            account = authenticate(username=MyUserAccount.objects.get(email=email).username,password=raw_password)
            if account is not None:
                login(request, account)
                return redirect('home')
    
        except:
            account = authenticate(username=email, password=raw_password)
            if account is not None:
                login(request, account)
                return redirect('home')
    

提交回复
热议问题