2016-01-12 21 views
1

我从Django 1.6升级到1.7,我遇到了一个棘手的问题。我有一个模型字段为资料图片如下:重构为Django 1.7可调用

profile_image = models.ImageField(
    upload_to=get_user_uploadto_callable('photos'), null=True, 
    verbose_name=_('photo'), blank=True) 

...和我get_user_uploadto_callable看起来是这样的:

def get_user_uploadto_callable(subdir): 
    '''Return a callable that returns a custom filepath/filename 
    for an uploaded file as per `get_user_upload_path`. 

    ''' 

    def _callable(instance, filename): 
     return get_user_upload_path(instance, subdir, filename) 

    return _callable 

但是这不再是可以接受的Django的,并导致该错误,当我试图让迁移:

ValueError: Could not find function _callable in myproj.core.util. 
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 

所以我需要移动此_callable方法外(可能它重命名为类似user_uploadto_callable),但小号直到有权访问传入的subdir参数。是否有干净的方式来做到这一点?

回答

1

不可能使用get_user_uploadto_callable的结果作为Python 2中的可调用对象,但是您可以定义一个执行相同操作的函数。

def profile_image_upload_to(): 
    # you can reduce this to one line if you prefer, I used 
    # two to make it clearer how it works 
    callable = get_user_uploadto_callable('photos') 
    return callable() 

class MyModel(models.Model): 
    profile_image = models.ImageField(
     upload_to=profile_image_upload_to, null=True, 
     verbose_name=_('photo'), blank=True) 
+0

不幸的是,这给了我同样的错误:看起来问题是'_callable'函数在另一个函数定义中。 – benwad

+0

谢谢,该版本的作品!理想情况下,虽然能够在字段定义中添加参数会很好,但是我知道在Python 2中使用Django的迁移系统可能无法实现。我会等一会接受这个答案,以防万一有什么魔法出现...... – benwad