Store ImageField file using id as filename

356 views
Skip to first unread message

gon...@gmail.com

unread,
Aug 29, 2009, 7:03:58 PM8/29/09
to Django users
I'm trying to store images using the admin interface with the id as
the filename.

class ProductImage(models.Model):
image = ImageField(upload_to=get_path)

def get_path(self, filename):
return 'product_images/%s.jpg' % self.id

However, the images get stored as 'product_images/None.jpg'...

Any ideas on how to approach this?

Thanks.

Mike Ramirez

unread,
Aug 29, 2009, 9:45:32 PM8/29/09
to django...@googlegroups.com

The id is generated when the model is saved for the first time. The db will
set the id, when autoincrement is set, on the insert statement, so you don't
have an id as the current point of saving the file. I would do something
like this:

from django.conf import settings
import os
class ProductImage(models.Model):
image = ImageField(upload_to='product_images/')

def save(self):
if self.id is None:
super(ProductImages, self).save()
self.image = self.get_path(self.image)
super(ProductImages, self).save()

def get_path(self, filename):
save_name = os.path.join*'product_images', '%s.jpg' % self.id)
current_path = os.path.join(settings.MEDIA_ROOT, self.image)
new_path = os.path.join(settings.MEDIA_ROOT, save_name)
if os.path.exists(current_path):
shutil.move(current_path, new_path)
return save_name

I'm not completely happy with this solution tho, it doesn't satisfy a few
things, such as if you change the image. I think the better way is to do this
during upload and have the upload handler[1] in your forms.py file and in
there generate a random name if you don't want the uplaoded name. From this
upload handler, just return the relative path for your ImageField to save. In
the admin just import this upload handler and overwrite the save_model[2]
method. There is one more option, on the post_save signal[3], you can do the
move/renaming there.

Hope this helps,

Mike

[1] http://docs.djangoproject.com/en/dev/topics/http/file-uploads/
[2] http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-methods
[3]
http://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.post_save
--
There is a certain impertinence in allowing oneself to be burned for an
opinion.
-- Anatole France

signature.asc

Gonçalo Ferreira

unread,
Aug 30, 2009, 11:03:21 AM8/30/09
to django...@googlegroups.com
Hi Mike,

Thanks a lot for the input!

I'll study all the alternatives you mentioned to see which suits my project better.

Again, thanks!

Gonçalo
Reply all
Reply to author
Forward
0 new messages