How to populate user profile with django-allauth provider information?

前端 未结 4 456
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 02:36

I\'m using django-allauth for my authentication system. I need that when the user sign in, the profile module get populated with the provider info (in my case facebook).

4条回答
  •  时光说笑
    2020-12-13 03:32

    Here is a Concrete example of @pennersr solution :

    Assumming your profile model has these 3 fields: first_name, email, picture_url

    views.py:

    @receiver(user_signed_up)
    def populate_profile(sociallogin, user, **kwargs):    
    
        if sociallogin.account.provider == 'facebook':
            user_data = user.socialaccount_set.filter(provider='facebook')[0].extra_data
            picture_url = "http://graph.facebook.com/" + sociallogin.account.uid + "/picture?type=large"            
            email = user_data['email']
            first_name = user_data['first_name']
    
        if sociallogin.account.provider == 'linkedin':
            user_data = user.socialaccount_set.filter(provider='linkedin')[0].extra_data        
            picture_url = user_data['picture-urls']['picture-url']
            email = user_data['email-address']
            first_name = user_data['first-name']
    
        if sociallogin.account.provider == 'twitter':
            user_data = user.socialaccount_set.filter(provider='twitter')[0].extra_data
            picture_url = user_data['profile_image_url']
            picture_url = picture_url.rsplit("_", 1)[0] + "." + picture_url.rsplit(".", 1)[1]
            email = user_data['email']
            first_name = user_data['name'].split()[0]
    
        user.profile.avatar_url = picture_url
        user.profile.email_address = email
        user.profile.first_name = first_name
        user.profile.save()         
    

    If you are confused about those picture_url variable in each provider. Then take a look at the docs:

    facebook:

    picture_url = "http://graph.facebook.com/" + sociallogin.account.uid + "/picture?type=large" Docs

    linkedin:

    picture_url = user_data['picture-urls']['picture-url'] Docs

    twitter:

    picture_url = picture_url.rsplit("_", 1)[0] + "." + picture_url.rsplit(".", 1)[1] Docs And for the rsplit() take a look here

    Hope that helps. :)

提交回复
热议问题