Django / Python:在保存文件前更改上传的文件名
我正在创建一个网站,用户可以在上面上传图片。我需要确保每个文件名都是独一无二的,这样文件才不会互相覆盖。我会生成这个独特的名字。但是,我该如何在保存文件之前更改文件名呢?我看到有方法可以改变文件保存的文件夹,但这并不是我想要的。
class saved_photos(models.Model):
name = models.CharField(max_length=20)
photo = models.ImageField(upload_to='images/things/', blank=True, null=True)
在我的代码中,我这样做:
new_name = get_unique_name()
p = saved_photos(name = new_name, photo = request.FILES)
p.save()
我需要的是保存的文件的实际名字是new_name。
3 个回答
0
这是一个自定义 upload_to 函数的例子,它根据实例的属性来设置文件名。
import posixpath
from django.utils.deconstruct import deconstructible
@deconstructible
class UploadToWithTpl:
"""Set Django file name based on instance attributes """
def __init__(self, upload_to_tpl):
self.upload_to_tpl = upload_to_tpl
def __call__(self, instance, filename):
if not filename:
return
new_name = replace_special_unicode_to_ascii(filename).strip()
if remove_substrings(new_name, ' ', *string.punctuation) == '':
new_name = 'file'
upload_to = self.upload_to_tpl.format(self=instance)
return posixpath.join(upload_to, new_name)
用法
class MyModel(models.Model):
hash = UniqueAutoGeneratedField()
json_file = models.FileField(
upload_to=UploadToWithTpl('protected/json_files', 'data_{self.hash}.json'))
1
Django可以正确处理文件名的唯一性。如果你上传的文件名重复,它会自动给这个文件改个名字。
如果你想手动设置文件名,只需像DrTyrsa说的那样定义一个upload_to
函数。这个问题可能对你有帮助。
8
你需要定义一个叫做 upload_to
的函数。