我剛剛將我的應用升級到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