我使用此代码创建重命名功能以在模型中重命名文件。
PGSSLMODE=verify-full PGSSLROOTCERT=server-ca.pem psql -h your_host -U your_user -W -d your_db
我使用这样的功能。
def path_and_rename(path):
def path_and_rename_func(instance, filename):
upload_to = path
ext = filename.split('.')[-1]
# get filename
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(upload_to, filename)
return path_and_rename_func
当我使用命令进行迁移image=models.ImageField(upload_to=path_and_rename("test_image"))
video=models.FileField(upload_to=path_and_rename("test_file"),blank=True, null=True)
它显示这样的错误。
python manage.py makemigrations
如何解决?
答案 0 :(得分:0)
您不能使用这种包装函数,因为这意味着结果函数没有限定名称。
但是,您可以定义两个辅助函数并使用它们,例如:
def path_and_rename_func(instance, filename, path):
upload_to = path
ext = filename.split('.')[-1]
# get filename
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(upload_to, filename)
def path_and_rename_test_image(instance, filename):
return path_and_rename(instance, filename, 'test_image')
def path_and_rename_test_file(instance, filename):
return path_and_rename(instance, filename, 'test_file')
class MyModel(models.Model):
image = models.ImageField(upload_to=path_and_rename_test_image)
video = models.FileField(
upload_to=path_and_rename_test_file,
blank=True,
null=True
)