3

Setup

I'm using Django 1.8.15 and django-allauth 0.28.0

Description

What I want to do is pretty easy to explain: If a user logs in via social media (facebook, google+ or twitter) i want to retrieve the extra_data from sociallogin to get the url to the avatar and other information to store it in my Profile, which is a One-to-one relation to my User model.

My approaches

1)

First I added a class with pre_social_login like here which gets called after the user has signed in via social media.

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'

I want to get the instance from the user but it seems, that it wasn't created yet. So I tried the following:

2)

I have another signal which creates a profile if a new user is added:

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()

I've added the following:

data = SocialAccount.objects.filter(user=instance)
# do more with data

but data it is always empty []

I have problems to understand that. I mean if a user logs in via social media and I can't access the user from User (case 1) because it wasn't created yet then the SocialAccountshould have been created when I try to get it in case 2?! Do you have any other ideas to solve that? Or am I missing something here?

Thanks in advance

Ébe Isaac
  • 11,563
  • 17
  • 64
  • 97
Kroenig
  • 644
  • 7
  • 16

1 Answers1

8

got it after some hours of desperation.

I've just used another signal user_signed_up, not the one from the 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

Kroenig
  • 644
  • 7
  • 16