Skip to main content
 首页 » 编程设计

python之使用电子邮件 ID 作为唯一 key 的自定义用户模型的 Django 身份验证

2024年10月24日39lidabo

为了在 email-id 上实现唯一约束(不重复默认用户模型字段),我这样做了

from django.contrib.auth.models import AbstractUser 
class User(AbstractUser): 
    # some extra fields 
    class Meta: 
        unique_together = ('email', ) 

然后在设置文件 AUTH_USER_MODEL = 'myApp.User'

mysql 表将两列(用户名和电子邮件)显示为 UNI 键。

到目前为止看起来还不错,但是当涉及到身份验证时,我不确定我在哪里犯了错误。但它不工作/登录

当用户名是唯一 key 并且我们通过用户名而不是电子邮件登录时,此代码有效。

任何帮助/线索将不胜感激。

编辑:我是否必须编写自定义模型后端(此处解释 http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/) 但不确定如何,我在这里看到很多代码 https://github.com/django/django/blob/master/django/contrib/auth/init.py

请您参考如下方法:

您需要像这样定义 backends.py:

from django.contrib.auth.models import User, check_password 
 
class EmailAuthBackend(object): 
""" 
Email Authentication Backend 
 
Allows a user to sign in using an email/password pair rather than 
a username/password pair. 
""" 
 
def authenticate(self, username=None, password=None): 
    """ Authenticate a user based on email address as the user name. """ 
    try: 
        user = User.objects.get(email=username) 
        if user.check_password(password): 
            return user 
    except User.DoesNotExist: 
        return None  
 
def get_user(self, user_id): 
    """ Get a User object from the user_id. """ 
    try: 
        return User.objects.get(pk=user_id) 
    except User.DoesNotExist: 
        return None 

然后在您的设置文件中添加:

AUTHENTICATION_BACKENDS = ('backends.EmailAuthBackend',) 

这将启用使用电子邮件登录。

有关更多详细信息,请访问 this .