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

标签 python django django-migrations

我刚刚将我的应用升级到 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/

相关文章:

json - JSONRenderer无法序列化:b'{“id”:“11122211133311”}}不可JSON序列化

django - 如何在 PyCharm 中禁用只读项目文件?

带有 CORS 转储数据的 Django 1.9 : "corsheaders_corsmodel" does not exist

django - 在Model.Meta中与Django GenericForeignKey一起使用CheckConstraint时出错-此查询中不允许联接的字段引用

python - 尽管单元测试正常运行,Authtoken 迁移仍无法正常工作

python - python的环境变量保存在哪里

python - 如何在Python中正确排序重音字母?

python - Django 在 CreateView 中禁用/排除字段,但在 UpdateView 中启用/包含它

python - 如何将for循环的结果存储为数组?

python - 如何对Python嵌套列表中的数据进行分类