Saturday, November 27, 2010

Django: Random Image/File Field name

By default, Django image/file fields place uploaded files in the MEDIA_ROOT directory, under a subdirectory given by the "upload_to" model field parameter.  However, the name of uploaded file is the same name as the original filename uploaded by the client.  The filename can be changed by creating a custom storage manager. 

---- myapp/storage.py
import os, itertools, random, string
from django.core.files.storage import FileSystemStorage

def rand_key(size):
    return "".join([random.choice(string.letters + string.digits)
                          for i in range(size)])

class RandomFileSystemStorage(FileSystemStorage):

    def get_valid_name(self, name):
        file_root, file_ext = os.path.splitext(name)
        return "%s%s" % (rand_key(32), file_ext)

    def get_available_name(self, name):
        dir_name, file_name = os.path.split(name)
        file_root, file_ext = os.path.splitext(file_name)
        count = itertools.count(1)
        while self.exists(name):
            name = os.path.join(dir_name, "%s_%s%s" % (
                             rand_key(32),  count.next(), file_ext))
        return name

---- myapp/models.py
from django.db import models
from myapp.storage import RandomFileSystemStorage

class Photo(models.Model):
    image = models.ImageField(upload_to='media',
                  storage=RandomFileSystemStorage())

No comments: