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

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

问题描述

在 django 中可以更改上传文件的文件名吗?我搜索过,但找不到任何答案.

我的要求是,无论何时上传文件,其文件名都应更改为以下格式.

format = userid + transaction_uuid + file_extension

非常感谢...

解决方案

你是如何上传文件的?我假设使用 FileField.

FileField 的文档.upload_to 表示 upload_to 字段,

<块引用>

也可以是可调用的,例如函数,它将被调用获取上传路径,包括文件名.这个可调用的必须能够接受两个参数,并返回一个Unix 风格的路径(带正斜杠)传递到存储系统.将成为的两个论点通过的是:

<块引用>

实例":一个实例FileField 所在的模型定义.更具体地说,这是特定情况下正在附加当前文件.

"filename":文件名最初给文件.这可能或者在以下情况下可能不被考虑确定最终目的地路径.

所以看起来你只需要创建一个函数来处理你的名字并返回路径.

def update_filename(instance, filename):路径=上传/路径/";格式 = instance.userid + instance.transaction_uuid + instance.file_extension返回 os.path.join(路径,格式)

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

Thank you very much...

解决方案

How are you uploading the file? I assume with the FileField.

The documentation for FileField.upload_to says that the upload_to field,

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": 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天全站免登陆