django信号,如何使用"instance" [英] django signals, how to use "instance"

查看:116
本文介绍了django信号,如何使用"instance"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个系统,使用户可以上传zip文件,然后使用post_save信号将其提取.

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 方法可以正常工作(在这种情况下,我需要提供 instance.file_zip.path .但是,我无法获取/设置带有信号的实例.关于信号的Django文档尚不清楚,也没有示例.那么,我该怎么办?

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?

推荐答案

实际上, Django的有关信号的文档非常清晰,并且确实包含示例.

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

在您的情况下, post_save 信号发送以下参数: sender (模型类), instance (类 sender 的实例),创建原始使用.如果您需要访问 instance ,则可以在示例中使用 kwargs ['instance'] 进行访问,或者最好将回调函数更改为接受参数:

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

这篇关于django信号,如何使用"instance"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆