Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
替换与imagefield关联的文件,而不让django复制它_Django - Fatal编程技术网

替换与imagefield关联的文件,而不让django复制它

替换与imagefield关联的文件,而不让django复制它,django,Django,我有一个表单的用户配置文件 class profile(): #the next line is just an abstract profile_images='volumes/media/root/userprofile/profile_images/' image=models.ImageField(upload_to=profile_images) 在“profile_images”目录中,有用户作为profile images上传的最后5个文件,即: image_1 im

我有一个表单的用户配置文件

class profile():
  #the next line is just an abstract
  profile_images='volumes/media/root/userprofile/profile_images/'
  image=models.ImageField(upload_to=profile_images)
在“profile_images”目录中,有用户作为profile images上传的最后5个文件,即:

image_1
image_2
image_3
image_4
image_5
假设当前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()
image_1
image_2
image_3
image_4
image_5
volumes/media/root/userprofile/profile_images/image_3
例如,用户选择图像_3,执行该代码后,前面提到的目录如下所示:

def change_profile_image(userprofile,path_to_new_image):
  f = open(path_to_new_image, 'r')
  userprofile.image = ImageFile(f)
  userprofile.save()
image_1
image_2
image_3
image_4
image_5
volumes/media/root/userprofile/profile_images/image_3
当然,这不是我想要的。我只想更改与我的配置文件实例的ImageField关联的文件,而不需要Django复制任何文件。

有什么办法解决这个问题吗?

理论上,你可以覆盖userprofile.image.path,但怎么做还不太清楚

这里有更多的信息


好的,实际上这很容易

userprofile.image=path_to_new_image

无需担心打开、删除和重写文件。

image.path不可写。你发布的问题正是我的方法。据我所知,我已经准备好将新文件写入userprofile.image。当我请求将userprofile.image.url(媒体url+文件的绝对路径)作为url时,我没有得到正确的url。这是否也会上载新文件?不是为我做的。