使用 django 强制执行唯一的上传文件名? [英] Enforce unique upload file names using django?

查看:26
本文介绍了使用 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 强制执行唯一的上传文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆