---- 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)
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())
storage=RandomFileSystemStorage())
No comments:
Post a Comment