我正在尝试创建一个系统,该系统使用户可以上传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()
当提供正确的文件路径时,
unzip_and_process
方法可以正常工作(在这种情况下,我需要提供instance.file_zip.path
。但是,我无法获取/设置带有信号的实例。有关信号的Django文档尚不清楚,并且没有例子,那我该怎么办?
最佳答案
实际上,Django's documentation about signals非常清楚,并包含示例。
在您的情况下,post_save
信号发送以下参数:sender
(模型类),instance
(类sender
的实例),created
,raw
和using
。如果需要访问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
# ...
关于django - django信号,如何使用“实例”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6992208/