我在其他地方找到了一些代码,以便在有现有电子邮件帐户时让django-rest-auth
与社交登录一起使用:
def pre_social_login(self, request, sociallogin):
"""
Invoked just after a user successfully authenticates via a
social provider, but before the login is actually processed
(and before the pre_social_login signal is emitted).
We're trying to solve different use cases:
- social account already exists, just go on
- social account has no email or email is unknown, just go on
- social account's email exists, link social account to existing user
"""
# Ignore existing social accounts, just do this stuff for new ones
if sociallogin.is_existing:
return
# some social logins don't have an email address, e.g. facebook accounts
# with mobile numbers only, but allauth takes care of this case so just
# ignore it
if 'email' not in sociallogin.account.extra_data:
return
# check if given email address already exists.
# Note: __iexact is used to ignore cases
try:
email = sociallogin.account.extra_data['email'].lower()
id = sociallogin.account.extra_data['id']
email_address = EmailAddress.objects.get(email__iexact=email)
# if it does not, let allauth take care of this new social account
except EmailAddress.DoesNotExist:
return
# if it does, connect this new social login to the existing user
user = email_address.user
profile = Profile.objects.get(email__iexact=email)
url = "http://graph.facebook.com/{}/picture?type=normal".format(id)
profile.media_url = url
profile.save() # suppose to persist to db, but isn't!!!
sociallogin.connect(request, user)
在连接帐户之前的最后几行中,我获得了FB帐户的个人资料图片并尝试将其保存到数据库中。对于我的生活,我无法理解为什么它不会保存网址。如果我使用django shell执行相同的命令,它会保存没有问题。如果有帮助,media_url
字段为URLField
。