7

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?

marue
  • 5,588
  • 7
  • 37
  • 65

2 Answers2

10

ok, actually it's as easy as

userprofile.image=path_to_new_image

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

marue
  • 5,588
  • 7
  • 37
  • 65
1

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?

Community
  • 1
  • 1
Arseny
  • 5,159
  • 4
  • 21
  • 24
  • image.path is not writeable. and you posted exactly the questions that pointed me to my approach. as far as i can see it, i allready wrote the new file to userprofile.image. i just don't get a correct url back, when asking for userprofile.image.url i get (MEDIA_URL+absolute path to the file) as url. – marue Jan 27 '11 at 16:01