django signals, how to use “instance”

末鹿安然 提交于 2021-02-04 13:09:12

问题


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?


回答1:


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



回答2:


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 


来源:https://stackoverflow.com/questions/6992208/django-signals-how-to-use-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!