Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace the file associated with an imagefield without having django copying it

Tags:

django

I have a userprofile of the 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 directory "profile_images" there are the last 5 files the user uploaded as profile images, ie:

image_1
image_2
image_3
image_4
image_5

lets say the current profile.image is image_1. now i want to allow the user to select one of the previous images. the function i wrote to change the image to the one i received from the form looks like that:

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 execution of that code the forementioned directory looks like that:

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. what i want is to just change the file associated with the ImageField of my profile instance, without Django copying any files.
any ideas how to solve that?

like image 209
marue Avatar asked Jan 27 '11 12:01

marue


2 Answers

ok, actually it's as easy as

userprofile.image=path_to_new_image

no need to worry with opening files, deleting and rewriting them.

like image 160
marue Avatar answered Nov 19 '22 05:11

marue


Theoretically, you could overwrite userprofile.image.path, but it’s not too obvious how to do that.

Here is some more information.

Programmatically saving image to Django ImageField

Django: How to replace/overwrite/update/change a file of FileField?

How can I replace/override an uploaded file?

like image 1
Arseny Avatar answered Nov 19 '22 06:11

Arseny