如何在Django中更改上传文件的文件名? [英] How to change the file name of an uploaded file in Django?

查看:97
本文介绍了如何在Django中更改上传文件的文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Django中更改已上传文件的文件名?我进行了搜索,但找不到任何答案。

Is it possible to change the file name of an uploaded file in django? I searched, but couldn't find any answer.

我的要求是,每当上传文件时,其文件名都应更改为以下格式。

My requirement is whenever a file is uploaded its file name should be changed in the following format.

format = userid + transaction_uuid + file_extension

非常感谢...

推荐答案

您如何上传文件?
我假设使用 FileField

FileField.upload_to 表示 upload_to 字段,


也可以是可调用的,例如
函数,它将被调用到
获取上传路径,包括
文件名。这个可调用对象必须能够使
接受两个参数,并返回
Unix风格的路径(带有正斜杠)
才能传递给存储
系统。传递
的两个参数是:

may also be a callable, such as a function, which will be called to obtain the upload path, including the filename. This callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments that will be passed are:

instance
的实例,其中 FileField 已定义为
。更具体地说,这是附加了
当前文件的特定实例

"instance": An instance of the model where the FileField is defined. More specifically, this is the particular instance where the current file is being attached.

文件名:最初给该文件的文件名
。当
决定最终目的地
路径时,可能会考虑
,也可能不会考虑。

"filename":The filename that was originally given to the file. This may or may not be taken into account when determining the final destination path.

所以看起来您只需要创建一个函数来进行名称处理并返回路径即可。

So it looks like you just need to make a function to do your name handling and return the path.

def update_filename(instance, filename):
    path = "upload/path/"
    format = instance.userid + instance.transaction_uuid + instance.file_extension
    return os.path.join(path, format)

这篇关于如何在Django中更改上传文件的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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