改写 django的 authenticate

from django.contrib.auth import authenticate

这里的authenticate默认的是使用username.
在我们创建的APP的views.py.添加


from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
class CustomBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username)|Q(email=username))  #Q是并集的意思,这里的email可以改成自己定义
            if user.check_password(password):
                return user
        except Exception as e:
            return None

这里的UserProfile是下面这样定义的

class UserProfile(AbstractUser):
from django.contrib.auth.models import AbstractUser

settings.py下添加
在这里插入图片描述

这里users是我的apps的名称。

猜你喜欢

转载自blog.csdn.net/qq_40965177/article/details/84984231