Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.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 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?

like image 865
Umur Kontacı Avatar asked Aug 09 '11 06:08

Umur Kontacı


2 Answers

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
    # ...
like image 69
Ferdinand Beyer Avatar answered Sep 18 '22 19:09

Ferdinand Beyer


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 
like image 32
Aaron Lelevier Avatar answered Sep 19 '22 19:09

Aaron Lelevier