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 On Sun, Aug 30, 2009 at 2:45 AM, Mike Ramirez <gufym...@gmail.com> wrote: > On Saturday 29 August 2009 04:03:58 pm gon...@gmail.com wrote: > > 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. > > > > 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 > --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---