我希望文件名是随机的,因此我使用upload_to
返回随机文件名的函数,如下所示:
from uuid import uuid4
import os
def get_random_filename(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (str(uuid4()), ext)
return os.path.join('some/path/', filename)
# inside the model
class FooModel(models.Model):
file = models.FileField(upload_to=get_random_filename)
但是我想将原始文件名保存到模型内的属性中。像这样的东西不起作用:
def get_random_filename(instance, filename):
instance.filename = filename
ext = filename.split('.')[-1]
filename = "%s.%s" % (str(uuid4()), ext)
return os.path.join('some/path/', filename)
# inside the model
class FooModel(models.Model):
file = models.FileField(upload_to=get_random_filename)
filename = models.CharField(max_length=128)
我该怎么做?
谢谢你。