Django Image Field Overwrite with ImageKit

I’m using django-imagekit on a new site. I was having a problem that when a user uploaded a new image for the object, the system would not overwrite the existing image file, but instead would create a new file with a sequence number on the end. This was not the behavior I was looking for. Lockjaw’s answer on StackExchange handled the not-overwriting the existing file problem. ImageKit was still caching the previous image for any specfields. The solution is to call ‘.clear()’ after saving the new image to purge the ImageKit cache for that specfield/image.

So, the total solution is:


#Lockjaw's code on StackExchange
class OverwriteStorage(FileSystemStorage):   
    def get_available_name(self, name):
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name

def issue_plane_image_path(plane, filename):
    "return the canonical file name for an image on this plane instance"
    extension = os.path.splitext(filename)[1]
    return os.path.join('photos/planes', plane.slug+extension) 

class Plane(models.Model):
    image = models.ImageField(upload_to=issue_plane_image_path, storage=OverwriteFileStorage(), null=True, blank=True)
    gallery = ImageSpecField(...)
    thumbnail = ImageSpecField(...) 

    def clearImageCache(self):
       "invalidate all ImageKit spec caches"
       self.gallery.clear()
       self.thumbnail.clear()

and in the edit view:


.
.
if form.is_valid():
   form.save()
   plane.clearImageCache()

And now each instance has very few images (usually only one, but if a person uploads different filetypes such as a PNG then a JPG, they will both exist. I am OK with that.)

This entry was posted in Django, Python. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>