我有一个注册表单,只询问电子邮件和密码。当用户注册时,django-allauth通过删除" @ email"来为该用户创建用户名。后缀构成用户的电子邮件地址。
例如,如果用户注册" some-user@example.com "他的用户名为" some-user "如果其他用户注册了" some-user@gmail.com "然后他的用户名将是" some-userr "
但我想要的是用户的用户名和电子邮件具有相同的价值。
那么如何配置django-allauth将用户名设置为用户电子邮件而不删除其后缀呢?
如果可能,如何在不创建自定义用户的情况下执行此操作。
在我的settings.py中:
#########################
# AllAuth Configuration #
#########################
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_PASSWORD_MIN_LENGTH = 8
答案 0 :(得分:10)
我确实想对用户pre_save上的信号做些什么。
您的设置看起来不错,因此如果您在某个地方添加以下代码(例如core.models.py
),它将按您的需要运行:
@receiver(pre_save, sender=User)
def update_username_from_email(sender, instance, **kwargs):
user_email = instance.email
username = user_email[:30]
n = 1
while User.objects.exclude(pk=instance.pk).filter(username=username).exists():
n += 1
username = user_email[:(29 - len(str(n)))] + '-' + str(n)
instance.username = username
我使用信号的原因是我希望每次保存用户时,都会更新用户名。您可以检查电子邮件是否已更改,仅在这种情况下更新用户名。
然后我将用户名限制为电子邮件的前30个字符(用户名的默认最大长度为30个字符):
username = user_email[:30]
您也可以更改用户名的最大长度,但在我的情况下,我更喜欢使用默认长度。
由于我这样做,可能会发生重复的用户名。为避免重复的用户名,如果在将限制为30个字符后生成的用户名已经存在,我将-2,-3 ...放在最后以使用户名唯一:
n = 1
while User.objects.exclude(pk=instance.pk).filter(username=username).exists():
n += 1
username = user_email[:(29 - len(str(n)))] + '-' + str(n)
instance.username = username
我希望这个解决方案可以帮到你!
答案 1 :(得分:0)
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
class CustomSocialAccountAdapter(DefaultSocialAccountAdapter):
def populate_user(self, request, sociallogin, data):
user = super().populate_user(request, sociallogin, data)
user.username = user.email
return user
SOCIALACCOUNT_ADAPTER = "profiles.models.CustomSocialAccountAdapter"