在使用django上传照片时,如何在服务器上以唯一的文件名重命名照片是最好的方法?我希望确保每个名称仅被使用一次。是否有任何pinax应用程序可以做到这一点,也许使用GUID?
在使用django上传照片时,如何在服务器上以唯一的文件名重命名照片是最好的方法?我希望确保每个名称仅被使用一次。是否有任何pinax应用程序可以做到这一点,也许使用GUID?
使用 uuid。 要将其与您的模型相关联,请参阅 Django 文档 中的 FileField upload_to。
例如,在您的 models.py 文件中定义以下函数:
import uuid
import os
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join('uploads/logos', filename)
接下来,在定义您的FileField/ImageField时,将get_file_path
指定为upload_to
值。
file = models.FileField(upload_to=get_file_path,
null=True,
blank=True,
verbose_name=_(u'Contact list'))
get_file_path
的函数。如果使用了upload_to=uuid4()
,那么你所提到的问题就会出现。 - orokusakiNameError: name 'get_file_path' is not defined
:( - NoobEditor一个更好的方法是在你的helpers.py中使用一个普通的类。这样,你可以在你的应用程序中重复使用随机文件生成器。
在你的helpers.py中:
import os
import uuid
from django.utils.deconstruct import deconstructible
@deconstructible
class RandomFileName(object):
def __init__(self, path):
self.path = os.path.join(path, "%s%s")
def __call__(self, _, filename):
# @note It's up to the validators to check if it's the correct file type in name or if one even exist.
extension = os.path.splitext(filename)[1]
return self.path % (uuid.uuid4(), extension)
然后在你的模型中,只需导入帮助类即可:
from mymodule.helpers import RandomFileName
然后使用它:
logo = models.ImageField(upload_to=RandomFileName('logos'))
参考:https://coderwall.com/p/hfgoiw/give-imagefield-uploads-a-unique-name-to-avoid-file-overwrites
截至本回答撰写时,似乎不再需要采取任何特殊措施才能实现此目的。如果使用静态upload_to
属性设置一个FileField
,Django存储系统将自动管理命名,以便在上传重复文件名时,Django会为副本生成一个新的唯一文件名。
在Django 1.10上有效。
get_avaialable_name
函数会通过添加下划线自动为文件命名以使其唯一。例如,如果您将一个名为“test.jpg”的文件保存到服务器上,然后再保存另一个名为“test.jpg”的文件,则第一个文件将被称为test.jpg,第二个文件将被称为test_1.jpg。FileField
并覆盖generate_filename
方法。class UniqueNameFileField(FileField):
def generate_filename(self, instance, filename):
_, ext = os.path.splitext(filename)
name = f'{uuid.uuid4().hex}{ext}'
return super().generate_filename(instance, name)
Django会自动强制执行唯一的文件名。如果文件已经存在,则会在文件名后添加七个唯一字符。
在Django 2.2上进行了测试。
get_available_name
。 - phoenix