Django - 无法使用动态upload_to值为ImageField创建迁移

ali*_*lix 27 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")
Run Code Online (Sandbox Code Playgroud)

当我尝试时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.
Run Code Online (Sandbox Code Playgroud)

ali*_*lix 64

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

根据这个错误报告,我编辑了我的代码:

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")
Run Code Online (Sandbox Code Playgroud)

然后,在字段定义中:

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")
Run Code Online (Sandbox Code Playgroud)

这对我有用.