Accepting email address as username in Django

后端 未结 12 2045
感动是毒
感动是毒 2020-11-28 19:48

Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user\'s email address instead of them creating a userna

12条回答
  •  醉梦人生
    2020-11-28 20:24

    The easiest way is to lookup the username based on the email in the login view. That way you can leave everything else alone:

    from django.contrib.auth import authenticate, login as auth_login
    
    def _is_valid_email(email):
        from django.core.validators import validate_email
        from django.core.exceptions import ValidationError
        try:
            validate_email(email)
            return True
        except ValidationError:
            return False
    
    def login(request):
    
        next = request.GET.get('next', '/')
    
        if request.method == 'POST':
            username = request.POST['username'].lower()  # case insensitivity
            password = request.POST['password']
    
        if _is_valid_email(username):
            try:
                username = User.objects.filter(email=username).values_list('username', flat=True)
            except User.DoesNotExist:
                username = None
        kwargs = {'username': username, 'password': password}
        user = authenticate(**kwargs)
    
            if user is not None:
                if user.is_active:
                    auth_login(request, user)
                    return redirect(next or '/')
                else:
                    messages.info(request, "Error User account has not been activated..")
            else:
                messages.info(request, "Error Username or password was incorrect.")
    
        return render_to_response('accounts/login.html', {}, context_instance=RequestContext(request))
    

    In your template set the next variable accordingly, i.e.

    And give your username / password inputs the right names, i.e. username, password.

    UPDATE:

    Alternatively, the if _is_valid_email(email): call can be replaced with if '@' in username. That way you can drop the _is_valid_email function. This really depends on how you define your username. It will not work if you allow the '@' character in your usernames.

提交回复
热议问题