django信号,如何使用"实例"

Umu*_*acı 15 django signals instance

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

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()
Run Code Online (Sandbox Code Playgroud)

unzip_and_process当提供正确的文件路径时,方法工作正常(在这种情况下,我需要提供instance.file_zip.path.但是,我无法使用信号获取/设置实例.关于信号的Django文档不清楚,没有示例.所以,做什么我做?

Fer*_*yer 22

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

在你的情况下,post_save信号发送下列参数:sender(模型类), instance(类的实例sender), ,created,rawusing.如果您需要访问instance,可以kwargs['instance']在示例中使用它来访问它,或者更好的是,更改您的回调函数以接受参数:

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