gpt4 book ai didi

django - 在 django-registration 中使用电子邮件作为用户名

转载 作者:行者123 更新时间:2023-12-02 00:06:49 28 4
gpt4 key购买 nike

我正在尝试使用电子邮件地址作为用户名(使用 Django 1.5 的自定义用户模型)以及 django-registration。

django-registration 1.0 版的文档说:-

the base view classes are deliberately user-model-agnostic. Simply subclass them, and implement logic for your custom user model

我已经对注册 View 进行了子类化,但不幸的是,RegistrationProfile 看起来仍然希望用户模型有一个用户名字段,而我的没有。我只有电子邮件(以及名字、姓氏等)

这是一个错误吗?在我看来,django-registration 仍然需要使用默认的基本用户模型——它只能使用将 ADDS 添加到基本模型的自定义用户模型。

有什么办法吗?也许我也可以将注册资料子类化?我该怎么做?

谢谢。

最佳答案

我认为,如果您继续使用默认用户配置文件,从长远来看,事情会变得更容易。如果您只是想添加使用电子邮件地址登录的功能,我建议创建一个新的身份验证后端:

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User


class EmailModelBackend(ModelBackend):
def authenticate(self, username=None, password=None):
try:
user = User.objects.get(email__iexact=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None

然后您需要将该后端连接到您的 settings.py:

AUTHENTICATION_BACKENDS = (
'yourproject.yourapp.yourmodule.EmailModelBackend',
'django.contrib.auth.backends.ModelBackend'
)

关于django - 在 django-registration 中使用电子邮件作为用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17830755/

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