开发者

django signals, how to use "instance"

I am trying to create a system which enables user to upload a zipfile, and then extract it using post_save signal.

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.op开发者_运维问答en(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 method works fine when correct file paths are provided(in this case, i need to provide instance.file_zip.path. However, I couldn't get/set the instance with the signals. Django documentation about signals is not clear and have no examples. So, what do I do?


Actually, Django's documentation about signals is very clear and does contain examples.

In your case, the post_save signals sends the following arguments: sender (the model class), instance (the instance of class sender), created, raw, and using. If you need to access instance, you can access it using kwargs['instance'] in your example or, better, change your callback function to accept the argument:

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


This worked for me when connecting Django Signals:

Here is the models.py:

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

And the Signal that access it post_save:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜