【发布时间】:2019-09-09 21:08:57
【问题描述】:
我在模型之外创建了一个函数,用作实用函数,只需将path 字符串传递给它,它就会返回文件路径和重命名的文件名。更改文件名的function(instance, filename) 被包装在一个接受path 字符串的包装函数中。
这是函数(存储在另一个应用程序中的helpers.py):
def path_and_rename(path):
"""
Returns wrapper func
:param path: path string with slash at the end
:return: func
"""
def wrapper(instance, filename):
"""
Returns a filename string, both
and filename, with filename as an md5 string
:param instance: model instance with the file_field or image_field
:param filename: filename as uploaded (as received from the model)
:return: str
"""
ext = filename.split('.')[-1] # Preserve image file extension
md5_file_name = f"{hashlib.md5(str(filename).encode('utf-8')).hexdigest()}.{ext}" # md5 from filename
return f"{path}{md5_file_name}"
return wrapper
在我的模型中,我做了以下事情:
image = ImageField(verbose_name=_("Product image"), upload_to=path_and_rename("products/images/"))
但这会在makemigrations 上产生错误:
'Could not find function %s in %s.\n' % (self.value.__name__, module_name)
ValueError: Could not find function wrapper in my_app_root.core.helpers.
【问题讨论】:
标签: django python-3.x django-models python-decorators higher-order-functions