Cant get post_save to work in Django

送分小仙女□ 提交于 2019-12-01 08:13:26

问题


I read the django docs about signals and wrote this piece of code for my model Car :

@receiver(request_finished)
def signal_callback(sender, **kwargs):
    print 'Save Signal received'


@receiver(post_save, sender=Car)
def signal_handler(sender, **kwargs):
    pass


request_finished(signal_callback, sender=car, dispatch_url="Unique save id")

But the problem is, that when I fire up my server, and just open up the admin, I get a lot of 'Save Signal received' in my terminal. What I am wondering about is I have restricted the signal_handler to post_save only. But still, without even saving anything, the message shows up a lot of times. I dont understand this.

Note : I will be honest. I understood parts of it, not everything from the documentation.


回答1:


There is a simpler way to bind post_save signals

from django.db.models.signals import post_save
from myapp.models import Car

def do_something(sender, **kwargs):
    print 'the object is now saved.'
    car = kwargs['instance'] #now i have access to the object

post_save.connect(do_something, sender=Car)

The signal request finished gets called every time a HTTP request is made, which is a hog.




回答2:


You binded request_finished signal to signal_callback. Remove(or comment out) signal_callback, and change signal_handler as follow.

@receiver(post_save, sender=Car)
def signal_handler(sender, **kwargs):
    print 'Save signal received'


来源:https://stackoverflow.com/questions/17257910/cant-get-post-save-to-work-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!