![](/img/trans.png)
[英]django-allauth include twitter email on sociallogin extra_data
[英]django django-allauth save extra_data from social login in signal
设定
我正在使用Django 1.8.15和django-allauth 0.28.0
描述
我想要做的是很容易解释:如果用户通过社交媒体登录(Facebook,谷歌+或Twitter)我要检索的extra_data
从sociallogin
得到的URL头像和其他信息,将其存储在我的Profile
,这是我的User
模型One-to-one relation
。
我的方法
1)
首先,我添加了一个类pre_social_login
喜欢这里的用户通过社交媒体在签署后调用。
models.py
class SocialAdapter(DefaultSocialAccountAdapter):
def pre_social_login(self, request, sociallogin):
"""Get called after a social login. check for data and save what you want."""
user = User.objects.get(id=request.user.id) # Error: user not available
profile = Profile(user=user)
picture = sociallogin.account.extra_data.get('picture', None)
if picture:
# ... code to save picture to profile
settings.py
SOCIALACCOUNT_ADAPTER = 'profile.models.SocialAdapter'
我想从用户那里获取实例,但似乎它还没有创建。 所以我尝试了以下方法:
2)
我有另一个信号,如果添加了新用户,它会创建一个配置文件:
models.py
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_profile_for_new_user(sender, created, instance, **kwargs):
"""Signal, that creates a new profile for a new user."""
if created:
profile = Profile(user=instance)
# following code was pasted here
profile.save()
我添加了以下内容:
data = SocialAccount.objects.filter(user=instance)
# do more with data
但data
总是空的[]
我有一些问题需要理解。 我的意思是,如果用户通过社交媒体登录,我无法从User
访问User
(案例1),因为它尚未创建,那么当我尝试在案例2中获取时,应该创建SocialAccount
? 你还有其他想法可以解决这个问题吗? 或者我在这里遗漏了什么?
提前致谢
经过几个小时的绝望之后得到了它。
我刚刚使用了另一个信号user_signed_up
,而不是socialaccount中的信号
from allauth.account.signals import user_signed_up
@receiver(user_signed_up)
def retrieve_social_data(request, user, **kwargs):
"""Signal, that gets extra data from sociallogin and put it to profile."""
# get the profile where i want to store the extra_data
profile = Profile(user=user)
# in this signal I can retrieve the obj from SocialAccount
data = SocialAccount.objects.filter(user=user, provider='facebook')
# check if the user has signed up via social media
if data:
picture = data[0].get_avatar_url()
if picture:
# custom def to save the pic in the profile
save_image_from_url(model=profile, url=picture)
profile.save()
http://django-allauth.readthedocs.io/en/latest/signals.html#allauth-account
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.