本文介绍了使用django强制执行唯一的上传文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用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 code> upload_to value。
file = models.FileField(upload_to = get_file_path, null = True, blank = True, verbose_name = _(u'Contact list'))
What's the best way to rename photos with a unique filename on the server as they are uploaded, using django? I want to make sure each name is used only once. Are there any pinax apps that can do this, perhaps with GUID?
解决方案Use uuid. To tie that into your model see Django documentation for FileField upload_to.
For example in your models.py define the following function:
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)Then, when defining your FileField/ImageField, specify get_file_path as the upload_to value.
file = models.FileField(upload_to=get_file_path, null=True, blank=True, verbose_name=_(u'Contact list'))
更多推荐
使用django强制执行唯一的上传文件名?
发布评论