使用django强制执行唯一的上传文件名?

编程入门 行业动态 更新时间:2024-10-20 07:52:20
本文介绍了使用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强制执行唯一的上传文件名?

本文发布于:2023-10-14 22:08:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492356.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件名   强制执行   上传   django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!