gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:28:54 38 4
gpt4 key购买 nike

为了在 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 .

关于python - 使用电子邮件 ID 作为唯一 key 的自定义用户模型的 Django 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31936237/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com