gpt4 book ai didi

python - Django - 无法为具有动态 upload_to 值的 ImageField 创建迁移

转载 作者:IT老高 更新时间:2023-10-28 22:20:12 26 4
gpt4 key购买 nike

我刚刚将我的应用升级到 1.7(实际上仍在尝试)。

这就是我在 models.py 中的内容:

def path_and_rename(path):
def wrapper(instance, filename):
ext = filename.split('.')[-1]
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(path, filename)
return wrapper

class UserProfile(AbstractUser):
#...
avatar = models.ImageField(upload_to=path_and_rename("avatars/"),
null=True, blank=True,
default="avatars/none/default.png",
height_field="image_height",
width_field="image_width")

当我尝试 makemigrations 时,它会抛出:

ValueError: Could not find function wrapper in webapp.models.
Please note that due to Python 2 limitations, you cannot serialize unbound method functions (e.g. a method declared
and used in the same class body). Please move the function into the main module body to use migrations.

最佳答案

我不确定是否可以回答我自己的问题,但我只是想通了(我认为)。

根据this bug report ,我编辑了我的代码:

from django.utils.deconstruct import deconstructible

@deconstructible
class PathAndRename(object):

def __init__(self, sub_path):
self.path = sub_path

def __call__(self, instance, filename):
ext = filename.split('.')[-1]
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(self.path, filename)

path_and_rename = PathAndRename("/avatars")

然后,在字段定义中:

avatar = models.ImageField(upload_to=path_and_rename,
null=True, blank=True,
default="avatars/none/default.png",
height_field="image_height",
width_field="image_width")

这对我有用。

关于python - Django - 无法为具有动态 upload_to 值的 ImageField 创建迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25767787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com