Django中的django-allauth如何在社交登录中保存extra_data到信号中?

3

设置

我使用的是Django 1.8.15和django-allauth 0.28.0。

描述

我想要做的事情很容易解释: 如果用户通过社交媒体(Facebook、Google+或Twitter)登录,我想要从sociallogin中检索extra_data来获取头像的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中访问用户(情况1),因为它还没有被创建,那么当我在情况2中尝试获取它时,SocialAccount应该已经被创建了!你有其他解决办法吗?或者我漏掉了什么重要的东西?

提前感谢

1个回答

8

经过几个小时的绝望之后,我得到了它。

我刚刚使用了另一个信号user_signed_up,而不是来自社交账户的信号。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接