Python 2.7 未绑定方法与 Django 1.7 迁移
Python 2.7 unbound method with Django 1.7 migrations
我正在升级到 Django 1.7.4 并使用新的内置迁移,但是在尝试 运行 makemigrations
:
时出现以下错误
ValueError: Could not find function upload_callback in app_utils.
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.For more information,
see https://docs.djangoproject.com/en/1.7/topics/migrations/#serializing-values
我的模型定义:
class Discount(models.Model):
banner = models.ImageField(
help_text=_("Banner image for this discount"),
upload_to=upload_to('discounts/', 'title'),
blank=True,
null=True
)
以及我在 app_utils.py
中的上传回调:
def upload_to(path, attribute=None):
def upload_callback(instance, filename):
compact = filename[:50]
try:
attr= unicode( slugify( getattr(instance, attribute) ) )
mypath = '%s/%s/%s' % (path, attr, compact)
except:
mypath = '%s%s' % (path, compact)
return mypath
return upload_callback
根据错误信息,表明upload_callback
未绑定。所以
我尝试将 upload_callback
拉出包装函数,但找不到将额外的 path
和 attribute
参数传入 upload_to
的方法。 Django 的文档并不清楚如何做到这一点,它只指定 instance
和 filename
是必需的。
理想情况下,我想要的是:
def upload_to(instance, filename, path, attribute=None):
...
我有什么想法可以实现这个目标吗?
在网络上认真深入挖掘之后,我发现了这个 Django 错误报告。该解决方案似乎创建了一个可调用工厂 class:
https://code.djangoproject.com/ticket/22999
更多讨论在这里:Django - Cannot create migrations for ImageField with dynamic upload_to value
我正在升级到 Django 1.7.4 并使用新的内置迁移,但是在尝试 运行 makemigrations
:
ValueError: Could not find function upload_callback in app_utils.
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.For more information,
see https://docs.djangoproject.com/en/1.7/topics/migrations/#serializing-values
我的模型定义:
class Discount(models.Model):
banner = models.ImageField(
help_text=_("Banner image for this discount"),
upload_to=upload_to('discounts/', 'title'),
blank=True,
null=True
)
以及我在 app_utils.py
中的上传回调:
def upload_to(path, attribute=None):
def upload_callback(instance, filename):
compact = filename[:50]
try:
attr= unicode( slugify( getattr(instance, attribute) ) )
mypath = '%s/%s/%s' % (path, attr, compact)
except:
mypath = '%s%s' % (path, compact)
return mypath
return upload_callback
根据错误信息,表明upload_callback
未绑定。所以
我尝试将 upload_callback
拉出包装函数,但找不到将额外的 path
和 attribute
参数传入 upload_to
的方法。 Django 的文档并不清楚如何做到这一点,它只指定 instance
和 filename
是必需的。
理想情况下,我想要的是:
def upload_to(instance, filename, path, attribute=None):
...
我有什么想法可以实现这个目标吗?
在网络上认真深入挖掘之后,我发现了这个 Django 错误报告。该解决方案似乎创建了一个可调用工厂 class:
https://code.djangoproject.com/ticket/22999
更多讨论在这里:Django - Cannot create migrations for ImageField with dynamic upload_to value