Log in user using either email address or username in Django

后端 未结 13 2566
故里飘歌
故里飘歌 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:17

    I thought I'd chuck my simpler approach in for anyone else who comes across this:

    # -*- coding: utf-8 -*-
    from django.contrib.auth import backends, get_user_model
    from django.db.models import Q
    
    
    class ModelBackend(backends.ModelBackend):
        def authenticate(self, username=None, password=None, **kwargs):
            UserModel = get_user_model()
    
            try:
                user = UserModel.objects.get(Q(username__iexact=username) | Q(email__iexact=username))
    
                if user.check_password(password):
                    return user
            except UserModel.DoesNotExist:
                # Run the default password hasher once to reduce the timing
                # difference between an existing and a non-existing user (#20760).
                UserModel().set_password(password)
    

    Note:

    • disregards USERNAME_FIELD, although you could add it back in pretty easily
    • case insensitive (you could just remove the __iexact's though to make it not)

提交回复
热议问题