def change_avatar(request, target_obj, target_type, from_name, extra_context={}, next_override=None, current_app='plus_groups', namespace='groups', **kwargs): # XXX some of this should probably be refactored into the model layer target = target_obj.get_ref() avatars = Avatar.objects.filter(target=target).order_by('-primary') if avatars.count() > 0: avatar = avatars[0] kwargs = {'initial': {'choice': avatar.id}} else: avatar = None kwargs = {} primary_avatar_form = PrimaryAvatarForm(request.POST or None, target=target, **kwargs) if request.method == "POST": if 'avatar' in request.FILES: path = avatar_file_path(target=target, filename=request.FILES['avatar'].name) avatar = Avatar( target=target, primary=True, avatar=path, ) new_file = avatar.avatar.storage.save(path, request.FILES['avatar']) avatar.save() request.user.message_set.create( message=_("Successfully uploaded a new avatar.")) if 'choice' in request.POST and primary_avatar_form.is_valid(): avatar = Avatar.objects.get( id=primary_avatar_form.cleaned_data['choice']) avatar.primary = True avatar.save() request.user.message_set.create( message=_("Successfully updated your avatar.")) return HttpResponseRedirect(next_override or _get_next(request)) return render_to_response( 'avatar/change.html', extra_context, context_instance=RequestContext( request, { 'avatar': avatar, 'avatars': avatars, 'primary_avatar_form': primary_avatar_form, 'next': next_override or _get_next(request), 'target': target_obj, 'target_type': target_type, 'from_name': from_name, }))
def change(request, extra_context={}, next_override=None): avatars = Avatar.objects.filter(user=request.user).order_by('-primary') if avatars.count() > 0: avatar = avatars[0] kwargs = {'initial': {'choice': avatar.id}} else: avatar = None kwargs = {} primary_avatar_form = PrimaryAvatarForm(request.POST or None, user=request.user, **kwargs) if request.method == "POST": updated = False if 'avatar' in request.FILES: path = avatar_file_path(user=request.user, filename=request.FILES['avatar'].name) avatar = Avatar( user=request.user, primary=True, avatar=path, ) new_file = avatar.avatar.storage.save(path, request.FILES['avatar']) avatar.save() updated = True request.user.message_set.create( message=_("Successfully uploaded a new avatar.")) if 'choice' in request.POST and primary_avatar_form.is_valid(): avatar = Avatar.objects.get( id=primary_avatar_form.cleaned_data['choice']) avatar.primary = True avatar.save() updated = True request.user.message_set.create( message=_("Successfully updated your avatar.")) if updated and notification: notification.send([request.user], "avatar_updated", { "user": request.user, "avatar": avatar }) if friends: notification.send( (x['friend'] for x in Friendship.objects.friends_for_user(request.user) ), "avatar_friend_updated", { "user": request.user, "avatar": avatar }) return HttpResponseRedirect(next_override or _get_next(request)) return render_to_response( 'avatar/change.html', extra_context, context_instance=RequestContext( request, { 'avatar': avatar, 'avatars': avatars, 'primary_avatar_form': primary_avatar_form, 'next': next_override or _get_next(request), }))
def change_avatar(request, id, extra_context={}, next_override=None): user_edit = get_object_or_404(User, pk=id) try: profile = Profile.objects.get(user=user_edit) except Profile.DoesNotExist: profile = Profile.objects.create_profile(user=user_edit) #if not has_perm(request.user,'profiles.change_profile',profile): raise Http403 if not profile.allow_edit_by(request.user): raise Http403 avatars = Avatar.objects.filter(user=user_edit).order_by('-primary') if avatars.count() > 0: avatar = avatars[0] kwargs = {'initial': {'choice': avatar.id}} else: avatar = None kwargs = {} primary_avatar_form = PrimaryAvatarForm(request.POST or None, user=user_edit, **kwargs) if request.method == "POST": updated = False if 'avatar' in request.FILES: path = avatar_file_path(user=user_edit, filename=request.FILES['avatar'].name) avatar = Avatar( user = user_edit, primary = True, avatar = path, ) new_file = avatar.avatar.storage.save(path, request.FILES['avatar']) avatar.save() updated = True request.user.message_set.create( message=_("Successfully uploaded a new avatar.")) if 'choice' in request.POST and primary_avatar_form.is_valid(): avatar = Avatar.objects.get(id= primary_avatar_form.cleaned_data['choice']) avatar.primary = True avatar.save() updated = True request.user.message_set.create( message=_("Successfully updated your avatar.")) if updated and notification: notification.send([request.user], "avatar_updated", {"user": user_edit, "avatar": avatar}) #if friends: # notification.send((x['friend'] for x in Friendship.objects.friends_for_user(user_edit)), "avatar_friend_updated", {"user": user_edit, "avatar": avatar}) return HttpResponseRedirect(reverse('profile', args=[user_edit.username])) #return HttpResponseRedirect(next_override or _get_next(request)) return render_to_response( 'profiles/change_avatar.html', extra_context, context_instance = RequestContext( request, {'user_this': user_edit, 'avatar': avatar, 'avatars': avatars, 'primary_avatar_form': primary_avatar_form, 'next': next_override or _get_next(request), } ) )
def handle(self, *args, **options): user_num = args[0] if len(args) > 0 else 1 response = urllib2.urlopen( "http://api.randomuser.me/?results=%s" % user_num) data = json.load(response) for u in data['results']: # Create user newUser = User() newUser.first_name = u['user']['name']['first'] newUser.last_name = u['user']['name']['last'] newUser.username = u['user']['username'] newUser.email = '%[email protected] ' % u['user']['username'] newUser.set_password(u['user']['username']) newUser.save() # Validate email address EmailAddress.objects.create(user=newUser, email=newUser.email, primary=True, verified=True) # Add avatar to user image_url = u['user']['picture']['large'] import requests import tempfile from django.core import files # Steam the image from the url request = requests.get(image_url, stream=True) # Create a temporary file lf = tempfile.NamedTemporaryFile( suffix='.' + request.url.split('/')[-1].split('.')[-1], prefix=newUser.username) # import ipdb # ipdb.set_trace() # Read the streamed image in sections for block in request.iter_content(1024 * 8): # If no more file then stop if not block: break # Write image block to temporary file lf.write(block) newAvatar = Avatar() newAvatar.avatar = files.File(lf) newAvatar.primary = True newAvatar.user = newUser newAvatar.save() self.stdout.write('New user created: %s.' % newUser) self.stdout.write('Successfully created %s new users.' % user_num)
def post(self, *args, **kwargs): avatar, avatars = _get_avatars(self.request.user) if 'add' in self.request.POST and 'avatar' in self.request.FILES: upload_avatar_form = UploadAvatarForm(self.request.POST, self.request.FILES, user=self.request.user) if upload_avatar_form.is_valid(): avatar = Avatar(user=self.request.user, primary=True) image_file = self.request.FILES['avatar'] avatar.avatar.save(image_file.name, image_file) avatar.save() messages.success(self.request, 'Successfully uploaded a new avatar.') avatar_updated.send(sender=Avatar, user=self.request.user, avatar=avatar) return HttpResponseRedirect(reverse('avatar_change')) elif 'change' in self.request.POST: primary_avatar_form = PrimaryAvatarForm(self.request.POST, user=self.request.user, avatars=avatars) if 'choice' in self.request.POST and primary_avatar_form.is_valid( ): avatar = Avatar.objects.get( id=primary_avatar_form.cleaned_data['choice']) avatar.primary = True avatar.save() avatar_updated.send(sender=Avatar, user=self.request.user, avatar=avatar) messages.success(self.request, 'Successfully updated your avatar.') return HttpResponseRedirect(reverse('avatar_change')) elif 'delete' in self.request.POST: delete_avatar_form = PrimaryAvatarForm(self.request.POST, user=self.request.user, avatars=avatars) if delete_avatar_form.is_valid(): ids = delete_avatar_form.cleaned_data['choice'] if six.text_type( avatar.id) in ids and avatars.count() > len(ids): for a in avatars: if six.text_type(a.id) not in ids: a.primary = True a.save() avatar_updated.send(sender=Avatar, user=self.request.user, avatar=avatar) break Avatar.objects.filter(id__in=ids).delete() messages.success(self.request, 'Selected avatar successfully deleted.') return HttpResponseRedirect(reverse('avatar_change')) return HttpResponseRedirect(reverse('avatar_change'))
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
def change_avatar(request, target_obj, target_type, from_name, extra_context={}, next_override=None, current_app='plus_groups',namespace='groups',**kwargs): # XXX some of this should probably be refactored into the model layer target = target_obj.get_ref() avatars = Avatar.objects.filter(target=target).order_by('-primary') if avatars.count() > 0: avatar = avatars[0] kwargs = {'initial': {'choice': avatar.id}} else: avatar = None kwargs = {} primary_avatar_form = PrimaryAvatarForm(request.POST or None, target=target, **kwargs) if request.method == "POST": if 'avatar' in request.FILES: path = avatar_file_path(target=target, filename=request.FILES['avatar'].name) avatar = Avatar( target = target, primary = True, avatar = path, ) new_file = avatar.avatar.storage.save(path, request.FILES['avatar']) avatar.save() request.user.message_set.create( message=_("Successfully uploaded a new avatar.")) if 'choice' in request.POST and primary_avatar_form.is_valid(): avatar = Avatar.objects.get(id= primary_avatar_form.cleaned_data['choice']) avatar.primary = True avatar.save() request.user.message_set.create( message=_("Successfully updated your avatar.")) return HttpResponseRedirect(next_override or _get_next(request)) return render_to_response( 'avatar/change.html', extra_context, context_instance = RequestContext( request, { 'avatar': avatar, 'avatars': avatars, 'primary_avatar_form': primary_avatar_form, 'next': next_override or _get_next(request), 'target' : target_obj, 'target_type' : target_type, 'from_name' : from_name, } ) )
def change(request, extra_context={}, next_override=None): avatars = Avatar.objects.filter(user=request.user).order_by('-primary') if avatars.count() > 0: avatar = avatars[0] kwargs = {'initial': {'choice': avatar.id}} else: avatar = None kwargs = {} primary_avatar_form = PrimaryAvatarForm( request.POST or None, user=request.user, **kwargs) if request.method == "POST": updated = False if 'avatar' in request.FILES: path = avatar_file_path(user=request.user, filename=request.FILES['avatar'].name) avatar = Avatar( user=request.user, primary=True, avatar=path, ) new_file = avatar.avatar.storage.save( path, request.FILES['avatar']) avatar.save() updated = True messages.info(request, _("Successfully uploaded a new avatar.")) if 'choice' in request.POST and primary_avatar_form.is_valid(): avatar = Avatar.objects.get(id= primary_avatar_form.cleaned_data['choice']) avatar.primary = True avatar.save() updated = True messages.info(request, _("Successfully updated your avatar.")) if updated and notification: notification.send([request.user], "avatar_updated", { "user": request.user, "avatar": avatar}) if friends: notification.send((x['friend'] for x in Friendship.objects.friends_for_user( request.user)), "avatar_friend_updated", {"user": request.user, "avatar": avatar}) return HttpResponseRedirect(next_override or _get_next(request)) return render_to_response( 'avatar/change.html', extra_context, context_instance=RequestContext( request, {'avatar': avatar, 'avatars': avatars, 'primary_avatar_form': primary_avatar_form, 'next': next_override or _get_next(request), } ) )
def _copy_avatar(request, user, account): import urllib2 from django.core.files.base import ContentFile from avatar.models import Avatar 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
def change(request, extra_context={}, next_override=None): avatars = Avatar.objects.filter(user=request.user).order_by("-primary") if avatars.count() > 0: avatar = avatars[0] kwargs = {"initial": {"choice": avatar.id}} else: avatar = None kwargs = {} primary_avatar_form = PrimaryAvatarForm(request.POST or None, user=request.user, **kwargs) if request.method == "POST": updated = False if "avatar" in request.FILES: path = avatar_file_path(user=request.user, filename=request.FILES["avatar"].name) avatar = Avatar(user=request.user, primary=True, avatar=path) new_file = avatar.avatar.storage.save(path, request.FILES["avatar"]) avatar.save() updated = True # request.user.message_set.create( # message=_("Successfully uploaded a new avatar.")) if "choice" in request.POST and primary_avatar_form.is_valid(): avatar = Avatar.objects.get(id=primary_avatar_form.cleaned_data["choice"]) avatar.primary = True avatar.save() updated = True # request.user.message_set.create( # message=_("Successfully updated your avatar.")) if updated and notification: notification.send([request.user], "avatar_updated", {"user": request.user, "avatar": avatar}) if friends: notification.send( (x["friend"] for x in Friendship.objects.friends_for_user(request.user)), "avatar_friend_updated", {"user": request.user, "avatar": avatar}, ) return HttpResponseRedirect(next_override or _get_next(request)) return render_to_response( "avatar/change.html", extra_context, context_instance=RequestContext( request, { "avatar": avatar, "avatars": avatars, "primary_avatar_form": primary_avatar_form, "next": next_override or _get_next(request), }, ), )
def change(request, extra_context={}, next_override=None): avatars = Avatar.objects.filter(user=request.user).order_by('-primary') if avatars.count() > 0: avatar = avatars[0] kwargs = {'initial': {'choice': avatar.id}} else: avatar = None kwargs = {} primary_avatar_form = PrimaryAvatarForm(request.POST or None, user=request.user, **kwargs) if request.method == "POST": if 'avatar' in request.FILES: path = avatar_file_path(user=request.user, filename=request.FILES['avatar'].name) try: os.makedirs(os.path.join( settings.MEDIA_ROOT, "/".join(path.split('/')[:-1]))) except OSError, e: pass # The dirs already exist. new_file = default_storage.open(path, 'wb') for i, chunk in enumerate(request.FILES['avatar'].chunks()): if i * 16 == MAX_MEGABYTES: raise Http404 # TODO: Is this the right thing to do? # Validation error maybe, instead? new_file.write(chunk) avatar = Avatar( user = request.user, primary = True, avatar = path, ) avatar.save() new_file.close() request.user.message_set.create( message=_("Successfully uploaded a new avatar.")) if 'choice' in request.POST and primary_avatar_form.is_valid(): avatar = Avatar.objects.get(id= primary_avatar_form.cleaned_data['choice']) avatar.primary = True avatar.save() request.user.message_set.create( message=_("Successfully updated your avatar.")) return HttpResponseRedirect(next_override or _get_next(request))
def change(request, extra_context={}, next_override=None): avatars = Avatar.objects.filter(user=request.user).order_by('-primary') if avatars.count() > 0: avatar = avatars[0] kwargs = {'initial': {'choice': avatar.id}} else: avatar = None kwargs = {} primary_avatar_form = PrimaryAvatarForm(request.POST or None, user=request.user, **kwargs) if request.method == "POST": if 'avatar' in request.FILES: path = avatar_file_path(user=request.user, filename=request.FILES['avatar'].name) avatar = Avatar( user = request.user, primary = True, avatar = path, ) new_file = avatar.avatar.storage.save(path, request.FILES['avatar']) avatar.save() request.user.message_set.create( message=_("Successfully uploaded a new avatar.")) if 'choice' in request.POST and primary_avatar_form.is_valid(): avatar = Avatar.objects.get(id= primary_avatar_form.cleaned_data['choice']) avatar.primary = True avatar.save() request.user.message_set.create( message=_("Successfully updated your avatar.")) return HttpResponseRedirect(next_override or _get_next(request)) return render_to_response( 'avatar/change.html', extra_context, context_instance = RequestContext( request, { 'avatar': avatar, 'avatars': avatars, 'primary_avatar_form': primary_avatar_form, 'next': next_override or _get_next(request), } ) )
def create_photo(request): error_message='' user_name='' form=FotosForm(request.POST, request.FILES) if not form.is_valid(): context = RequestContext(request, {'form': form, 'mensagem_erro': error_message}) return render_to_response('cadastro/ppassos/new_photos.html',context) try: user_name=request.user.username member=User.objects.get(pk=request.user.id) if 'foto_perfil' in request.FILES: photo_profile=Avatar() photo_profile.avatar=request.FILES['foto_perfil'] photo_profile.user=member photo_profile.primary=True photo_profile.save() if 'foto_divulgacao01' in request.FILES: photo=Image() photo.title=u'Foto de divulgação 01' photo.image=request.FILES['foto_divulgacao01'] photo.member=member photo.save() if 'foto_divulgacao02' in request.FILES: photo=Image() photo.title=u'Foto de divulgação 02' photo.image=request.FILES['foto_divulgacao02'] photo.member=member photo.save() except Exception,e: error_message=u'<p style="color:#f00 !important;">Desculpe %s, mas houve um erro interno. Por favor entre em contato com [email protected].<br>%s</p>' % (user_name,e) context = RequestContext(request, {'form': form, 'mensagem_erro': error_message}) return render_to_response('cadastro/ppassos/new_photos.html',context)
def post(self, request, format=None): self.get_initial_data() cropped = json.loads(request.POST.get('cropped', 'false')) if cropped: error = None avatar_file = StringIO(base64.b64decode(request.POST['photo'])) width, height = Image.open(avatar_file).size if width > settings.AVATAR_MAX_WIDTH: error = 'The width is more than %s pixels' % settings.AVATAR_MAX_WIDTH if height > settings.AVATAR_MAX_HEIGHT: error = 'The height is more than %s pixels' % settings.AVATAR_MAX_HEIGHT if error is not None: return Response(error) else: avatar_file = request.FILES['file'] file_type = imghdr.what(avatar_file) path = avatar_file_path(self.user, file_type, 'avatar') Avatar.objects.filter(user=self.user).delete() avatar = Avatar(user=self.user, avatar=path, primary=True) avatar.primary = True avatar.avatar.storage.save(path, avatar_file) avatar.save() return Response()
def change(request, img_url=None, extra_context=None, next_override=None, upload_form=UploadAvatarForm, primary_form=PrimaryAvatarForm, make_primary=False, *args, **kwargs): if extra_context is None: extra_context = {} avatar, avatars = _get_avatars(request.user) if avatar: kwargs = {'initial': {'choice': avatar.id}} else: kwargs = {} upload_avatar_form = upload_form(request.POST or None, request.FILES or None, user=request.user) primary_avatar_form = primary_form(request.POST or None, user=request.user, avatars=avatars, **kwargs) if 'url' in request.REQUEST: img_url = request.REQUEST['url'] if request.method == "GET" and img_url: upload_avatar_form = upload_form({'url': img_url}, request.FILES or None, user=request.user) if upload_avatar_form.is_valid(): return make(request, img_url, next_override='%s?next=%s' % (reverse('avatar_change'), _get_next(request))) if request.method == "POST": updated = False if 'avatar' in request.FILES: if upload_avatar_form.is_valid(): avatar = Avatar(user=request.user, primary=make_primary) image_file = request.FILES['avatar'] avatar.avatar.save(image_file.name, image_file) avatar.save() messages.success(request, _(AVATAR_UPLOADED_MSG)) if make_primary: updated = True if 'url' in request.POST and upload_avatar_form.is_valid(): return make(request, img_url, make_primary=make_primary, next_override=_get_next(request)) if 'choice' in request.POST and primary_avatar_form.is_valid(): avatar = Avatar.objects.get( id=primary_avatar_form.cleaned_data['choice']) avatar.primary = True avatar.save() updated = True if updated: messages.success(request, _(AVATAR_UPDATED_MSG)) avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar) return HttpResponseRedirect(next_override or _get_next(request)) return render_to_response( 'avatar/change.html', extra_context, context_instance=RequestContext( request, { 'avatar': avatar, 'avatars': avatars, 'upload_avatar_form': upload_avatar_form, 'primary_avatar_form': primary_avatar_form, 'next': next_override or _get_next(request), }))
def change_avatar(request, id, extra_context={}, next_override=None): user_edit = get_object_or_404(User, pk=id) try: profile = Profile.objects.get(user=user_edit) except Profile.DoesNotExist: profile = Profile.objects.create_profile(user=user_edit) #if not has_perm(request.user,'profiles.change_profile',profile): raise Http403 if not profile.allow_edit_by(request.user): raise Http403 avatars = Avatar.objects.filter(user=user_edit).order_by('-primary') if avatars.count() > 0: avatar = avatars[0] kwargs = {'initial': {'choice': avatar.id}} else: avatar = None kwargs = {} primary_avatar_form = PrimaryAvatarForm(request.POST or None, user=user_edit, **kwargs) if request.method == "POST": updated = False if 'avatar' in request.FILES: path = avatar_file_path(user=user_edit, filename=request.FILES['avatar'].name) avatar = Avatar( user=user_edit, primary=True, avatar=path, ) new_file = avatar.avatar.storage.save(path, request.FILES['avatar']) avatar.save() updated = True messages.add_message(request, messages.SUCCESS, _("Successfully uploaded a new avatar.")) if 'choice' in request.POST and primary_avatar_form.is_valid(): avatar = Avatar.objects.get( id=primary_avatar_form.cleaned_data['choice']) avatar.primary = True avatar.save() updated = True messages.add_message(request, messages.SUCCESS, _("Successfully updated your avatar.")) if updated and notification: notification.send([request.user], "avatar_updated", { "user": user_edit, "avatar": avatar }) #if friends: # notification.send((x['friend'] for x in Friendship.objects.friends_for_user(user_edit)), "avatar_friend_updated", {"user": user_edit, "avatar": avatar}) return HttpResponseRedirect( reverse('profile', args=[user_edit.username])) #return HttpResponseRedirect(next_override or _get_next(request)) return render_to_response( 'profiles/change_avatar.html', extra_context, context_instance=RequestContext( request, { 'user_this': user_edit, 'avatar': avatar, 'avatars': avatars, 'primary_avatar_form': primary_avatar_form, 'next': next_override or _get_next(request), }))
from django.core.files.base import ContentFile contentf = ContentFile(pdata) _log.debug("... creating avatar...") #contentf.name = 'xf-vcard-auto-avatar' autobasename = 'xf-vcard-auto-avatar.%s' contentf.name = autobasename % extension autoav = Avatar(user=user, avatar=contentf) # Check if auto-avatar is already presemt, replace if it is. # ! It's user's problem if user uploads an avatar with such a special # name :) old_autoav_qs = Avatar.objects.filter(user=user, avatar__startswith=avatar_file_path(autoav, autobasename % ''))[:1] if old_autoav_qs: # Already have some. Replace it. # ! XXX: non-parallel-safe here. old_autoav = old_autoav_qs[0] autoav.primary = old_autoav.primary # XXX: Not very nice. old_autoav.delete() else: # save the new one, autoav.save() _log.debug("... av done.") def processcmd(indata): """ Processes XMPP-originating data such as statuses, text commands, etc. """ src = indata.get('src') srcbarejid = src.split("/")[0] # Strip the resource if any. dst = indata.get('dst') body = indata.get('body') _log.debug(" -+-+-+-+-+- indata: %r." % indata) if 'auth' in indata: # Got subscribe/auth data. Save it.