Kro*_*nig 3 python django django-allauth
设置
我正在使用 Django 1.8.15 和 django-allauth 0.28.0
描述
我想要做的很容易解释:如果用户通过社交媒体(facebook、google+ 或 twitter)登录,我想检索extra_datafromsociallogin以获取头像的 url 和其他信息以将其存储在我的Profile.一One-to-one relation到我的User模型。
我的方法
1)
首先,我添加了一个pre_social_login类似here的类,它在用户通过社交媒体登录后被调用。
模型.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
Run Code Online (Sandbox Code Playgroud)
设置.py
SOCIALACCOUNT_ADAPTER = 'profile.models.SocialAdapter'
Run Code Online (Sandbox Code Playgroud)
我想从用户那里获取实例,但它似乎尚未创建。所以我尝试了以下方法:
2)
如果添加新用户,我还有另一个信号可以创建配置文件:
模型.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()
Run Code Online (Sandbox Code Playgroud)
我添加了以下内容:
data = SocialAccount.objects.filter(user=instance)
# do more with data
Run Code Online (Sandbox Code Playgroud)
但data它总是空的 []
我有问题无法理解。我的意思是,如果用户通过社交媒体登录并且我无法从User(案例 1)访问该用户,因为它尚未创建,那么SocialAccount当我在案例 2 中尝试获取它时应该已经创建了?!你有其他想法来解决这个问题吗?还是我在这里遗漏了什么?
提前致谢
几个小时的绝望后得到了它。
我刚刚使用了另一个信号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()
Run Code Online (Sandbox Code Playgroud)
http://django-allauth.readthedocs.io/en/latest/signals.html#allauth-account
| 归档时间: |
|
| 查看次数: |
1917 次 |
| 最近记录: |