您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

根据此错误报告,我编辑了代码

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")

这对我有用。

Go 2022/1/1 18:30:09 有329人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶