python - 为重命名文件创建函数后,Django 无法迁移模型
问题描述
我使用此代码为模型中的重命名文件创建重命名函数。
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
它显示这样的错误。
ValueError: Could not find function path_and_rename_func in Test.models.
如何解决?
解决方案
您不能使用此类包装函数,因为这意味着生成的函数没有限定名称。
但是,您可以定义两个辅助函数并使用它们,例如:
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
)
推荐阅读
- python - 我的 django 视图总是抛出“意外的关键字参数错误
- excel - 将列从一个工作簿复制到另一个
- excel - 在符合模式的文件夹中打开文件的最新版本
- javascript - 我无法在 React.js 中访问“this.props.match.params.id”
- javascript - React 有太多的重新渲染问题
- excel - 如何在 excel 中实现这种自定义数字格式?
- javascript - Discord.js 机器人命令
- parsing - 从具有隐含节点和无序子节点的 ASTNode 创建 PsiElement
- c# - 当我单击它时,GetMouseButtonDown unity c#SCRIPT 不起作用
- amazon-web-services - s3 存储桶通过 http 代理集成从 lambda 访问的正确公共访问配置是什么?