def add(request, user_id, extra_context={}, next_override=None, *args, **kwargs): avatar, avatars = _get_avatars(user_id) user = User.objects.get(pk=user_id) upload_avatar_form = UploadAvatarForm(request.POST or None, request.FILES or None, user=user) if request.method == "POST" and 'avatar' in request.FILES: if upload_avatar_form.is_valid(): avatar = Avatar( user = user, primary = True, ) image_file = request.FILES['avatar'] avatar.avatar.save(image_file.name, image_file) avatar.save() updated = True user.message_set.create( message=_(u"刚上传了一个新的头像。")) if notification: _notification_updated(request, avatar) return render_to_response( 'avatar/add.html', extra_context, context_instance = RequestContext( request, { 'avatar': avatar, 'hey_user': user, 'avatars': avatars, 'upload_avatar_form': upload_avatar_form, 'next': next_override or _get_next(request), } ) )
def avatar_crop(request, id=None): """ Avatar management, creates a new avatar and makes it default """ user = User.objects.get(pk=1) if id: user = User.objects.get( pk = id) avatar = get_object_or_404(Avatar, id=id, user=user) print avatar else: avatar = get_object_or_404(Avatar, user=user, primary=True) if (avatar.avatar.width<=avatar.avatar.height): result = "width" else: result = "height" if not request.method == "POST": form = AvatarCropForm() else: try: orig = avatar.avatar.storage.open(avatar.avatar.name, 'rb').read() image = Image.open(StringIO(orig)) except IOError: return form = AvatarCropForm(image, request.POST) if form.is_valid(): top = int(form.cleaned_data.get('top')) left = int(form.cleaned_data.get('left')) right = int(form.cleaned_data.get('right')) bottom = int(form.cleaned_data.get('bottom')) box = [ left, top, right, bottom ] (w, h) = image.size if result=="width": box = map(lambda x: x*h/AVATAR_CROP_MAX_SIZE, box) else: box = map(lambda x: x*w/AVATAR_CROP_MAX_SIZE, box) image = image.crop(box) if image.mode != 'RGB': image = image.convert('RGB') thumb = StringIO() image.save(thumb, "JPEG") thumb_file = ContentFile(thumb.getvalue()) base_name, ext = os.path.splitext(avatar.avatar.name) thumb = avatar.avatar.storage.save("%s_cropped%s" % (base_name, ext), thumb_file) Avatar.objects.filter(id=avatar.id).update(primary=False) new_avatar = Avatar(user=user, primary=True, avatar=thumb) new_avatar.save() user.message_set.create(message="修改了头像") return HttpResponseRedirect(reverse("avatar_change",args=(user.id,))) c = { 'AVATAR_CROP_MAX_SIZE':AVATAR_CROP_MAX_SIZE, 'dim':result, 'avatar': avatar, 'form': form } c.update(csrf(request)) return render_to_response("avatar_crop/crop.html", c)