About Re-generating Versions for a Particular Image with django-imagekit

The django-imagekit library creates image versions with filenames based on hashed values. That's quite tricky to track. Here is an example function to find existing versions and re-generate them in the file system:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def regenerate_versions(source):
    from django.core.files.storage import default_storage
    from imagekit.registry import generator_registry
    from imagekit.cachefiles import ImageCacheFile

    for id in generator_registry.get_ids():
        generator = generator_registry.get(id, source=source)
        image_cache_file = ImageCacheFile(generator)
        if default_storage.exists(image_cache_file.name):
            default_storage.delete(image_cache_file.name)
            image_cache_file.generate()

Then you can call it for an image field:

1
2
post = Post.objects.get(slug="hello-world")
regenerate_versions(post.cover_image)

Tips and Tricks Programming Development Django 4.2 Django 3.2 Django 2.2 Pillow django-imagekit