Of the several libraries/packages available for setting up social network logins for Django projects, I currently find django-allauth the most complete, with the best docs and the most active development. Doesn’t hurt that the lead dev on the project is super friendly and responsive on StackOverflow!
But not everything about it is intuitive. After wiring up Twitter, Facebook and Google as login providers, I found that first and last names were not being retrieved from the remote services when an account was successfully created. I also, frustratingly, could find only the most oblique references online to how to accomplish this.
There are a couple of ways to go about it – you can either receive and handle the allauth.account.signals.user_signed_up
signal that allauth emits on success, or set up allauth.socialaccount.adapter.DefaultSocialAccountAdapter
, which is also unfortunately barely documented.
I decided to go the signals route. The key to making this work is in intercepting the sociallogin
parameter your signal handler will receive when an account is successfully created. I then installed a breakpoint with import pdb; pdb.set_trace()
to inspect the contents of sociallogin
. Once I had access to those goodies, I was able to post-populate the corresponding User objects in the database.
This sample code grabs First/Last names from Twitter, Facebook or Google; season to taste:
Code:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | from allauth.account.signals import user_signed_up
from django.dispatch import receiver
@receiver (user_signed_up)
def user_signed_up_(request, user, sociallogin = None , * * kwargs):
if sociallogin:
if sociallogin.account.provider = = 'twitter' :
name = sociallogin.account.extra_data[ 'name' ]
user.first_name = name.split()[ 0 ]
user.last_name = name.split()[ 1 ]
if sociallogin.account.provider = = 'facebook' :
user.first_name = sociallogin.account.extra_data[ 'first_name' ]
user.last_name = sociallogin.account.extra_data[ 'last_name' ]
if sociallogin.account.provider = = 'google' :
user.first_name = sociallogin.account.extra_data[ 'given_name' ]
user.last_name = sociallogin.account.extra_data[ 'family_name' ]
user.save()
|