django 信号,如何使用“实例”
我正在尝试创建一个系统,使用户能够上传 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 文档不清楚并且没有示例,那么我该怎么办?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,Django 关于信号的文档非常清楚并且包含示例。
在您的情况下,
post_save
信号发送以下参数:sender
(模型类)、instance
(sender
类的实例)、created、<代码>原始和
来访问它,或者更好的是,更改回调函数以接受参数:使用
。如果您需要访问实例,可以在示例中使用 kwargs['instance']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 classsender
),created
,raw
, andusing
. If you need to accessinstance
, you can access it usingkwargs['instance']
in your example or, better, change your callback function to accept the argument:这在连接
Django Signals
时对我有用:这是models.py:
以及访问它的Signalpost_save >:
This worked for me when connecting
Django Signals
:Here is the models.py:
And the Signal that access it post_save: