很抱歉快速回答,这是解决您问题的另一种方法:这里的想法是为每个上传的文件创建一个唯一的文件夹。
# in your settings.py file
MY_FILE_PATH = 'stored_files/'
您的文件将被存储的路径:/public/media/stored_files
# somewhere in your project create an utils.py file
import random
try:
from hashlib import sha1 as sha_constructor
except ImportError:
from django.utils.hashcompat import sha_constructor
def generate_sha1(string, salt=None):
"""
Generates a sha1 hash for supplied string.
:param string:
The string that needs to be encrypted.
:param salt:
Optionally define your own salt. If none is supplied, will use a random
string of 5 characters.
:return: Tuple containing the salt and hash.
"""
if not isinstance(string, (str, unicode)):
string = str(string)
if isinstance(string, unicode):
string = string.encode("utf-8")
if not salt:
salt = sha_constructor(str(random.random())).hexdigest()[:5]
hash = sha_constructor(salt+string).hexdigest()
return (salt, hash)
在你的models.py
from django.conf import settings
from utils.py import generate_sha1
def upload_to_unqiue_folder(instance, filename):
"""
Uploads a file to an unique generated Path to keep the original filename
"""
salt, hash = generate_sha1('{}{}'.format(filename, get_datetime_now().now))
return '%(path)s%(hash_path)s%(filename)s' % {'path': settings.MY_FILE_PATH,
'hash_path': hash[:10],
'filename': filename}
#And then add in your model fileField the uplaod_to function
class MyModel(models.Model):
file = models.FileField(upload_to=upload_to_unique_folder)
该文件将上传到此位置:
公共/媒体/stored_file_path/unique_hash_folder/my_file.extention
注意:我从Django userena来源获得了代码,并根据我的需要对其进行了调整
注意2:有关更多信息,请查看有关 Django 文件上传的这篇精彩文章:文件上传示例
祝你有美好的一天。
编辑:试图提供一个可行的解决方案:)