def edit_avatar(request): """Edit user avatar.""" try: user_profile = request.user.get_profile() except Profile.DoesNotExist: # TODO: Once we do user profile migrations, all users should have a # a profile. We can remove this fallback. user_profile = Profile.objects.create(user=request.user) if request.method == "POST": # Upload new avatar and replace old one. old_avatar_path = None if user_profile.avatar and os.path.isfile(user_profile.avatar.path): # Need to store the path, not the file here, or else django's # form.is_valid() messes with it. old_avatar_path = user_profile.avatar.path form = AvatarForm(request.POST, request.FILES, instance=user_profile) if form.is_valid(): if old_avatar_path: os.unlink(old_avatar_path) user_profile = form.save() content = _create_image_thumbnail(user_profile.avatar.path, settings.AVATAR_SIZE, pad=True) # We want everything as .png name = user_profile.avatar.name + ".png" # Delete uploaded avatar and replace with thumbnail. user_profile.avatar.delete() user_profile.avatar.save(name, content, save=True) return HttpResponseRedirect(reverse("users.edit_profile")) else: # request.method == 'GET' form = AvatarForm(instance=user_profile) return render(request, "users/edit_avatar.html", {"form": form, "profile": user_profile})
def edit_avatar(request): """Edit user avatar.""" try: user_profile = Profile.objects.get(user=request.user) except Profile.DoesNotExist: # TODO: Once we do user profile migrations, all users should have a # a profile. We can remove this fallback. user_profile = Profile.objects.create(user=request.user) if user_profile.is_fxa_migrated: raise Http404 if request.method == 'POST': # Upload new avatar and replace old one. old_avatar_path = None if user_profile.avatar and os.path.isfile(user_profile.avatar.path): # Need to store the path, not the file here, or else django's # form.is_valid() messes with it. old_avatar_path = user_profile.avatar.path form = AvatarForm(request.POST, request.FILES, instance=user_profile) if form.is_valid(): if old_avatar_path: os.unlink(old_avatar_path) user_profile = form.save() content = _create_image_thumbnail(user_profile.avatar.path, settings.AVATAR_SIZE, pad=True) # We want everything as .png name = user_profile.avatar.name + ".png" # Delete uploaded avatar and replace with thumbnail. user_profile.avatar.delete() user_profile.avatar.save(name, content, save=True) return HttpResponseRedirect(reverse('users.edit_my_profile')) else: # request.method == 'GET' form = AvatarForm(instance=user_profile) return render(request, 'users/edit_avatar.html', { 'form': form, 'profile': user_profile })