public
Last active

Support for copying profile pictures into django-avatar was removed from django-allauth. This gist contains example code that you can drop into your own project in order to reinstate that functionality.

  • Download Gist
allauth_avatar.py
Python
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
import urllib2
 
from django.template.defaultfilters import slugify
from django.core.files.base import ContentFile
from django.dispatch import receiver
 
from avatar.models import Avatar
from allauth.account.signals import user_signed_up
 
 
def name_from_url(url):
"""
>>> name_from_url('http://google.com/dir/file.ext')
u'file.ext'
>>> name_from_url('http://google.com/dir/')
u'dir'
>>> name_from_url('http://google.com/dir')
u'dir'
>>> name_from_url('http://google.com/dir/..')
u'dir'
>>> name_from_url('http://google.com/dir/../')
u'dir'
>>> name_from_url('http://google.com')
u'google.com'
>>> name_from_url('http://google.com/dir/subdir/file..ext')
u'file.ext'
"""
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
p = urlparse(url)
for base in (p.path.split('/')[-1],
p.path,
p.netloc):
name = ".".join(filter(lambda s: s,
map(slugify, base.split("."))))
if name:
return name
 
 
def copy_avatar(request, user, account):
url = account.get_avatar_url()
if url:
ava = Avatar(user=user)
ava.primary = Avatar.objects.filter(user=user).count() == 0
try:
content = urllib2.urlopen(url).read()
name = name_from_url(url)
ava.avatar.save(name, ContentFile(content))
except IOError:
# Let's nog make a big deal out of this...
pass
 
 
@receiver(user_signed_up)
def on_user_signed_up(sender, request, *args, **kwargs):
sociallogin = kwargs.get('sociallogin')
if sociallogin:
copy_avatar(request,
sociallogin.account.user,
sociallogin.account)

ok, great. Any suggestions as to where to put this file? How do I make sure django finds it?

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.