Log in user using either email address or username in Django

后端 未结 13 2584
故里飘歌
故里飘歌 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 09:11

    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.

提交回复
热议问题