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' , )