Replace the file associated with the image field without copying django

I have a userprofile form

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

in the profile_images directory there are the last 5 files that the user uploaded as profile images, that is:

 image_1 image_2 image_3 image_4 image_5 

lets say that the current profile.image is image_1. Now I want to allow the user to select one of the previous images. the function that I wrote to change the image to the one I received from the form is as follows:

 def change_profile_image(userprofile,path_to_new_image): f = open(path_to_new_image, 'r') userprofile.image = ImageFile(f) userprofile.save() 

as an example, the user selects image_3, and after executing this code, the drop-down directory looks like this:

 image_1 image_2 image_3 image_4 image_5 volumes/media/root/userprofile/profile_images/image_3 

which, of course, is not what I wanted. I want to just modify the file associated with the ImageField of my profile instance, without Django copying any files.
any ideas how to solve this?

+4
source share
2 answers

ok, actually it's as simple as

 userprofile.image=path_to_new_image 

No need to worry about opening files, deleting and rewriting.

+3
source

Theoretically, you can overwrite userprofile.image.path, but it is not too obvious how to do this.

Here is some more information.

Programmatically save image to Django ImageField

Django: how to replace / overwrite / update / modify FileField file?

How to replace / override the downloaded file?

+1
source

Source: https://habr.com/ru/post/1337308/


All Articles