Django pre_save信号不起作用 [英] Django pre_save signal does not work

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

问题描述

我以下列方式测试了Django的pre_save信号,但无法捕捉到任何一个信号。

I tested the "pre_save" signal of Django in the following ways, but cannot catch the signal in either of them.

$

from django.db.models.signals import pre_save
import logging

def my_callback(sender, **kwargs):
    logging.debug("======================================")
pre_save.connect(my_callback)




  1. 运行manage.py shell中的以上代码:
    然后我运行我的网站,看到models.save()成功工作,但回调函数不运行。

  1. Run the above code in manage.py shell: Then I run my website and see models.save() work successfully, but the callback function does not run.

或者,我再次在shell上运行上面的代码,然后在shell中运行models.save()。 save再次起作用,但回调函数仍然没有任何反应。

Alternatively, I run the above code on shell again and then run models.save() in the shell. "save" works well again but still nothing happens to the callback function.

最后,我将上述代码嵌入到一个 __ init__中。 py 文件,仍然在网站上运行save()函数。仍然没有发生任何事情。

Finally, I embed the above code in an __init__.py file and still, run the save() function on the website. Still, nothing occurs.

你能帮我找出为什么pre_save信号似乎不起作用吗?

Would you please help me figure out why pre_save signal seems not work?

推荐答案

您没有设置发件人类。

from django.db.models.signals import pre_save
from myapp.models import MyModel
import logging

def my_callback(sender, **kwargs):
    logging.debug("======================================")
pre_save.connect(my_callback, sender=MyModel)

其次,如果你使用Django 1.3你应该使用新的装饰器语法。

Secondly, if you're using Django 1.3 you should use the new decorator syntax.

# Inside your models.py
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver

class MyModel(models.Model):
    field1 = models.TextField()
    field2 = models.IntegerField()

@receiver(pre_save, sender=MyModel)
def mymodel_save_handler(sender, **kwargs):
    logging.debug("======================================")

应该这样做,但是我还没有测试代码所以让我知道如果它还是坏了。

That should do it, but I haven't tested the code so let me know if it's still broken.

这篇关于Django pre_save信号不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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