3

I have some code found elsewhere on SO to get django-rest-auth to work with social login when there is an existing email account:

def pre_social_login(self, request, sociallogin):
    """
    Invoked just after a user successfully authenticates via a
    social provider, but before the login is actually processed
    (and before the pre_social_login signal is emitted).

    We're trying to solve different use cases:
    - social account already exists, just go on
    - social account has no email or email is unknown, just go on
    - social account's email exists, link social account to existing user
    """

    # Ignore existing social accounts, just do this stuff for new ones
    if sociallogin.is_existing:
        return

    # some social logins don't have an email address, e.g. facebook accounts
    # with mobile numbers only, but allauth takes care of this case so just
    # ignore it
    if 'email' not in sociallogin.account.extra_data:
        return

    # check if given email address already exists.
    # Note: __iexact is used to ignore cases
    try:
        email = sociallogin.account.extra_data['email'].lower()
        id = sociallogin.account.extra_data['id']
        email_address = EmailAddress.objects.get(email__iexact=email)


    # if it does not, let allauth take care of this new social account
    except EmailAddress.DoesNotExist:
        return

    # if it does, connect this new social login to the existing user
    user = email_address.user
    profile = Profile.objects.get(email__iexact=email) 
    url = "http://graph.facebook.com/{}/picture?type=normal".format(id)
    profile.media_url = url 
    profile.save() # suppose to persist to db, but isn't!!!
    sociallogin.connect(request, user)

In the last few lines there before connecting the accounts, I get the profile pic of the FB account and try to save it to the database. For the life of me, I can't understand why it won't save the url. If I do the same commands using django shell, it saves with no problem. The media_url field is a URLField if that helps.

John Moutafis
  • 22,254
  • 11
  • 68
  • 112
Evan Zamir
  • 8,059
  • 14
  • 56
  • 83
  • Does this method executed during user login? If you add print(email) before `profile.save()` can you see it in console? – neverwalkaloner Feb 08 '18 at 06:12
  • Is it going through till profile.save()? – Jahongir Rahmonov Feb 08 '18 at 06:13
  • It's supposed to occur before login, yes. And yes I can see print statements in the console. The thing is the rest of the code works fine. It logs the user in. But even after login, I don't see the update in the db. It's very strange. It even prints out `print(profile.media_url)`. – Evan Zamir Feb 08 '18 at 06:13
  • Can you get and post the SQL queries for us? https://stackoverflow.com/questions/4375784/log-all-sql-queries – Dylan Feb 08 '18 at 23:17

0 Answers0