替换与图像字段关联的文件,而无需django复制它

mar*_*rue 5 django

我有一个表单的userprofile

class profile():
  #the next line is just an abstract
  profile_images='volumes/media/root/userprofile/profile_images/'
  image=models.ImageField(upload_to=profile_images)
Run Code Online (Sandbox Code Playgroud)

在"profile_images"目录中,用户上传的最后5个文件为个人资料图片,即:

image_1
image_2
image_3
image_4
image_5
Run Code Online (Sandbox Code Playgroud)

让我们说当前的profile.image是image_1.现在我想让用户选择以前的图像之一.我写的函数将图像更改为从表单中收到的图像看起来像:

def change_profile_image(userprofile,path_to_new_image):
  f = open(path_to_new_image, 'r')
  userprofile.image = ImageFile(f)
  userprofile.save()
Run Code Online (Sandbox Code Playgroud)

作为示例,用户选择image_3,并且在执行该代码之后,前述目录看起来像:

image_1
image_2
image_3
image_4
image_5
volumes/media/root/userprofile/profile_images/image_3
Run Code Online (Sandbox Code Playgroud)

当然,这不是我想要的.我想要的只是更改与我的配置文件实例的ImageField相关联的文件,而不是Django复制任何文件.
任何想法如何解决?

mar*_*rue 6

好的,实际上就像它一样容易

userprofile.image=path_to_new_image
Run Code Online (Sandbox Code Playgroud)

无需担心打开文件,删除和重写它们.