Django 使用 用户名 或者 邮箱名进行登录验证

views.py

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.contrib.auth.models import AbstractUser, Group, User

class CustomBackend(ModelBackend):
    """邮箱也能登录"""
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user=User.objects.get(Q(username=username)|Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

settings.py

AUTHENTICATION_BACKENDS=( 'system.views.CustomBackend' , )