def avatar(request): upload = UploadAvatarForm() retrieve = RetrieveImageForm() choose = ChooseWallpaperForm() is_valid, rerrors = False, [] if request.method == 'POST': post = request.POST.copy() profile = request.user.get_profile() if post.get('action') == 'upload': upload = UploadAvatarForm(post, request.FILES) if upload.is_valid(): ufile, uerrors = handle_upload(request.FILES['file']) avatar = handle_avatar(ufile, profile) set_avatar(avatar.id, request.user.get_profile()) return HttpResponseRedirect(reverse('account-index')) elif post.get('action') == 'url': retrieve = RetrieveImageForm(post) if retrieve.is_valid(): rfile, rerrors = retrieve_url(post.get('url')) if not rerrors: avatar = handle_avatar(rfile, profile) set_avatar(avatar, request.user.get_profile()) return HttpResponseRedirect(reverse('account-index')) elif post.get('action') == 'wallpaper': choose = ChooseWallpaperForm(post) return pick_wallpaper(post.get('token')) elif post.get('action') == 'previous': if post.get('avatar') != None: set_avatar(post.get('avatar'), request.user.get_profile()) return HttpResponseRedirect(reverse('account-index')) return 'avatar.html', {'upload_form': upload, 'retrieve_form': retrieve, 'choose_form': choose, 'retrieve_errors': rerrors}
def make_avatar(request, *args, **kwargs): model = kwargs.get('model') match = kwargs.get('match') file = kwargs.get('file') keyword = kwargs.get('keyword') qargs = {match: keyword} instance = model.objects.get(**qargs) file_path = instance.__getattribute__(file) if not file_path.startswith(settings.MEDIA_ROOT): file_path = settings.MEDIA_ROOT + file_path avatar = handle_avatar(open(file_path, 'r+b'), request.user.get_profile(), remove_original=False) set_avatar(avatar.id, request.user.get_profile()) return HttpResponseRedirect(next(request))