Software Enthusiastic
Software Enthusiastic

Reputation: 26425

Image field related problems while using in django admin

I have a following Banner class. Which is editable by admin.

class Banner(models.Model):
    name        = models.CharField(max_length = 128)
    link        = models.TextField(max_length = 450)
    image       = models.ImageField(upload_to = 'banner_images')

There are two problems.

  1. When saving image it is saved with original file name. I would like to change it with some unique name so that is not clashed when image with the same name is uploaded again in the specified directory.
  2. While updating the image, the first image file must be deleted. It is not happening...

Any suggestion will be helpful. Thanks in advance.

Upvotes: 1

Views: 389

Answers (3)

Software Enthusiastic
Software Enthusiastic

Reputation: 26425

Since I was having problem related to savings of image through admin I got following solution which answers all my queries...

  • First I found that even though admin keeps the original file name, if the file with same name already exists, it keeps on appending a count as a suffix to prevent duplicate file name... for example, if same file is uploaded it is stored as image, image_2, image_3 etc...

  • Second, while changing image through admin, it was not removing the original file. For that I wrote following code in admin.py. And it does the job well...

Code:

class BannerAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        #Remove the previous file if the object is not new 
        #and new file supplied.        
        if obj.id != None and len(request.FILES) > 0:

            import os
            old_obj = m.Banner.objects.get(id = obj.id)
            os.remove(old_obj.image.path)

Hope this helps you if you have got the similar problem.

Upvotes: 0

Willian
Willian

Reputation: 2445

1) upload_to can be a callable, on save you can modify it's filename (docs)

2) see https://code.djangoproject.com/ticket/6792, you have to delete it yourself,

Upvotes: 0

Gabriel Ross
Gabriel Ross

Reputation: 5198

Try something like this:

from os import rename
class Banner(models.Model):
    name        = models.CharField(max_length = 128)
    link        = models.TextField(max_length = 450)
    image       = models.ImageField(upload_to = 'banner_images')

    def save(self):
            super(Banner, self).save()
            new_filename = <insert code here to change name>
            self.image.name = new_filename
            rename(static_path+'banner_images/'+self.image, static_path+'banner_images/'+new_filename)
            super(Banner, self).save()

I'm not sure if the super(Banner, self).save() called is required twice or not. The 1st might be needed to save the file, and the 2nd one to update the DB record.

Upvotes: 1

Related Questions