Skip to content

Instantly share code, notes, and snippets.

@Brick85
Created August 22, 2013 11:54
Show Gist options
  • Save Brick85/6306247 to your computer and use it in GitHub Desktop.
Save Brick85/6306247 to your computer and use it in GitHub Desktop.
# forms.py
class UserProfileForm(forms.ModelForm):
class Meta:
model = User
fields = ("email", "last_name", "first_name", "middle_name", 'avatar', 'age', 'hobbies', 'about', 'project_interes')
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super(UserProfileForm, self).__init__(*args, **kwargs)
for fname in ("email", "last_name", "first_name", 'age'):
self.fields[fname].required=True
avatars = [('upload', u'Загрузить с диска')]
if self.instance.is_movescount_authorised(self.request):
avatars.append(('movescount', u'Взять с Movescount'))
for social in self.instance.get_connected_socials():
avatars.append((social, u"Взять с {0}".format(settings.SOCIALS[social])))
if len(avatars) != 1:
self.fields['avatar_source'] = forms.ChoiceField(choices=avatars, initial="upload")
self.fields.keyOrder = ["email", "last_name", "first_name", "middle_name", 'avatar_source', 'avatar', 'age', 'hobbies', 'about', 'project_interes']
def clean_email(self):
email = self.cleaned_data.get('email')
if self.instance:
user = self.instance
if email and User.objects.filter(email=email).exclude(pk=user.pk).count():
raise forms.ValidationError(u'Такая электронная почта уже существует.')
return email
def save(self, *args, **kwargs):
user = super(UserProfileForm, self).save(*args, **kwargs)
if 'avatar_source' in self.cleaned_data and self.cleaned_data['avatar_source'] != 'upload':
avatar_source = self.cleaned_data['avatar_source']
url, new_filename = user.get_avatar_url(avatar_source=avatar_source)
if url:
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(urllib2.urlopen(url).read())
img_temp.flush()
user.avatar.save(new_filename, File(img_temp))
return user
# models.py
class User:
def get_avatar_url(self, avatar_source):
img_url = None
new_filename = ''
if avatar_source == 'movescount':
from movescount.api import Movescount
msc = Movescount(self)
ret = msc.do_action('GET', 'members/private')
if ret.parsed:
img = ret.data['ImageURI']
if img:
img = img.replace('.png', '_222.png')
img_url = img
new_filename = "movescount_{0}.png".format(self.pk)
elif avatar_source == 'facebook':
social_auth_item = self.social_auth.filter(provider="facebook")[0]
img_url = "https://graph.facebook.com/{0}/picture?width=500&height=500".format(social_auth_item.uid)
new_filename = "facebook_{0}.jpg".format(self.pk)
elif avatar_source == 'vk-oauth':
import urllib2
social_auth_item = self.social_auth.filter(provider="vk-oauth")[0]
api_url = "https://api.vkontakte.ru/method/users.get?uid={0}&fields=photo_max".format(social_auth_item.uid)
vk_resp = json.loads(urllib2.urlopen(api_url).read())
img = vk_resp['response'][0]['photo_max']
if img != 'http://vk.com/images/camera_b.gif':
img_url = img
new_filename = "vk_{0}.jpg".format(self.pk)
elif avatar_source == 'twitter':
from twython import Twython
from urlparse import parse_qs
social_auth_item = self.social_auth.filter(provider="twitter")[0]
auth_data = parse_qs(social_auth_item.extra_data['access_token'])
t = Twython(app_key=settings.TWITTER_CONSUMER_KEY,
app_secret=settings.TWITTER_CONSUMER_SECRET,
oauth_token=auth_data['oauth_token'][0],
oauth_token_secret=auth_data['oauth_token_secret'][0])
user_data = t.show_user(user_id=social_auth_item.uid)
img_url = user_data['profile_image_url'].replace('_normal.jpg', '.jpg')
new_filename = "twitter_{0}.jpg".format(self.pk)
return img_url, new_filename
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment