2011-08-09 25 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