Login or Sign up

Generate a unique filename for Django FileField, ImageField, etc

Posted by: skyl on Oct. 25, 2009

If Django tries to upload a file and finds a filename already at that location, the default behavior is to append a '_' to the filename and save it. However, this is not a scalable solution in that OSes can not store filenames of countably infinite characters.

I was storing some thumbnails for an OEmbed (I might show some of the other code later). I couldn't just let the filename get longer and longer as we aggregated more and more content. So, I used this little generate_filename() function to make a unique name with the time. Hopefully it makes sense. If not, maybe I can clarify and show more code. The bottom line is that the kwarg, upload_to can be a callable and can point to an filename, not just a directory.

import os
import time
from imagekit.models import ImageModel

def generate_filename(instance, old_filename):
    extension = os.path.splitext(old_filename)[1]
    filename = str(time.time()) + extension
    return 'thumbs/' + filename

class ThumbCache(ImageModel):
    image = models.ImageField(upload_to=generate_filename)

    class IKOptions:
        # This inner class is where we define the ImageKit options for the model
        spec_module = 'myproject.oembed.specs'
        cache_dir = 'thumbs'

Comments on This Post:

Please Login (or Sign Up) to leave a comment