Skip to content

Instantly share code, notes, and snippets.

@dchaplinsky
Created September 28, 2011 18:12
Show Gist options
  • Save dchaplinsky/1248728 to your computer and use it in GitHub Desktop.
Save dchaplinsky/1248728 to your computer and use it in GitHub Desktop.
Get avatars from social networks (facebook and google) with django-social-auth
from social_auth.backends.facebook import FacebookBackend
from social_auth.backends import google
def social_extra_values(sender, user, response, details, **kwargs):
result = False
if "id" in response:
from apps.photo.models import Photo
from urllib2 import urlopen, HTTPError
from django.template.defaultfilters import slugify
from apps.account.utils import user_display
from django.core.files.base import ContentFile
try:
url = None
if sender == FacebookBackend:
url = "http://graph.facebook.com/%s/picture?type=large" \
% response["id"]
elif sender == google.GoogleOAuth2Backend and "picture" in response:
url = response["picture"]
if url:
avatar = urlopen(url)
photo = Photo(author = user, is_avatar = True)
photo.picture.save(slugify(user.username + " social") + '.jpg',
ContentFile(avatar.read()))
photo.save()
except HTTPError:
pass
result = True
return result
pre_update.connect(social_extra_values, sender=None)
@Cruel
Copy link

Cruel commented Nov 22, 2011

Thanks a lot!
You can add this for Twitter too:

        elif sender == TwitterBackend:
            url = response["profile_image_url"]

@cedricpinson
Copy link

Where do you insert this code in a django app ?

@dchaplinsky
Copy link
Author

It lives in my models.py for user accounts.

However I think you can plug it in any file in any app which is discoverable.

@kouroshshafi
Copy link

I don't know why when I add this to my model, I get into some weird loop that forces login again!!! without the snippet I am good? any idea why?

(This webpage has a redirect loop)

@kouroshshafi
Copy link

I have redone your code to fetch the photo upon registration. https://gist.github.com/1662930

@Nawaj2417
Copy link

i have to show the profile image from google while login in django from the template . Anyone , please help me?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment