自定义信号不起作用
我创建了一个信号:
sig_published = Signal()
该信号放置在 signal.py 中,我将其导入到 models.py 中:
from signals import sig_published
在模型文件的页脚中,我将其连接到一个函数,该函数出于测试目的仅打印出调试字符串。:
def update_mode(sender, **kwargs):
print "UPDATING"
sig_published.connect(update_mode, sender=MyModel)
现在,在我的 save() 方法中,我尝试发送一个信号:
sig_published.send(sender=self)
但它没有打印出任何内容。如果我尝试使用像 pre_save 这样的内置信号:
pre_save.connect(update_mode, sender=MyModel)
它会起作用。有什么想法吗?
I created a signal:
sig_published = Signal()
This signal is placed in a signals.py, which I import in my models.py:
from signals import sig_published
and in the model file's footer, I connect it to a function which for testing purposes just prints out a debug string.:
def update_mode(sender, **kwargs):
print "UPDATING"
sig_published.connect(update_mode, sender=MyModel)
Now, in my save()-Method, I try to send a signal:
sig_published.send(sender=self)
but it does not print out anything. If I try a built-in signal like pre_save:
pre_save.connect(update_mode, sender=MyModel)
it works. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用等于模型实例的
sender
发出信号,而在连接中则与MyModel
class。这两个不是同一个对象,因此您的接收器会忽略该信号。您可以与pre_save
发出代码,它使用类,而不是实例。You're emitting the signal with
sender
equal to your model's instance, while in connect you're matching againstMyModel
class. Those two aren't the same object, so your receiver ignores the signal. You can compare withpre_save
emitting code, that it uses a class, not an instance.