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

编程入门 行业动态 更新时间:2024-10-20 05:33:18
本文介绍了使用 django 强制执行唯一的上传文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在上传照片时,使用 django 在服务器上使用唯一文件名重命名照片的最佳方法是什么?我想确保每个名称只使用一次.是否有任何 pinax 应用程序可以做到这一点,也许带有 GUID?

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?

推荐答案

使用 uuid.要将其绑定到您的模型中,请参阅 DjangoFileField upload_to 的文档.

Use uuid. To tie that into your model see Django documentation for FileField upload_to.

例如在您的 models.py 中定义以下函数:

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)

然后,在定义 FileField/ImageField 时,将 get_file_path 指定为 upload_to 值.

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

发布评论

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

>www.elefans.com

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