我刚刚将我的应用升级到1.7(实际上仍在尝试)。Django - 无法为具有动态upload_to值的ImageField创建迁移
这是我在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.
我认为这是正确的解决方案。 – 2014-09-10 14:30:56
是否可以使用它,并为每个字段添加一个自定义文件路径? – 2014-11-14 12:50:25
@ Garreth00是的,将文件路径作为参数传递给'PathAndRename'类。例如:'custom_path = PathAndRename(“/ profiles/bg-images”)' – alix 2014-11-14 13:44:45