2011-08-09 34 views
14

我想创建一个系统,使用户能够上传zipfile,然后使用post_save信号提取它。当设置正确的文件路径django信号,如何使用“实例”

class Project: 
    .... 
    file_zip=FileField(upload_to='projects/%Y/%m/%d') 

@receiver(post_save, sender=Project) 
def unzip_and_process(sender, **kwargs): 
    #project_zip = FieldFile.open(file_zip, mode='rb') 
    file_path = sender.instance.file_zip.path 
    with zipfile.ZipFile(file_path, 'r') as project_zip: 
     project_zip.extractall(re.search('[^\s]+(?=\.zip)', file_path).group(0)) 
     project_zip.close() 

unzip_and_process法正常工作(在这种情况下,我需要提供instance.file_zip.path,但我不能让/与信号设置的实例。有关信号Django文档不清晰?并没有例子所以,我该怎么办

回答

19

其实,Django's documentation about signals是很清楚,确实包含例子

在你的情况下,post_save信号发送下列参数:sender(模型类), instance(inst类别sender),created,rawusing。连接Django Signals

@receiver(post_save, sender=Project) 
def unzip_and_process(sender, instance, created, raw, using, **kwargs): 
    # Now *instance* is the instance you want 
    # ... 
+0

我认为这是** ** kwargs',我还不知道。你的例子很好,谢谢。 –

+0

@Ferdinand在django文档中没有关于post_save的示例。 – Anuj

+0

@Anuj - 我从来没有说过有关'post_save'的任何例子。有一些关于如何使用信号的例子,这些也适用于'post_save',因为这个特定的信号没有什么特别之处。 –

1

这个工作对我来说:如果您需要访问instance,您可以访问它使用在你的榜样kwargs['instance']或者更好的,改变你的回调函数接受参数

这里在models.py

class MyModel(models.Model): 
    name = models.CharField(max_length=100) 

而且信号访问它post_save

@receiver(post_save, sender=MyModel) 
def print_name(sender, instance, **kwargs): 
    print '%s' % instance.name