Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django pre_save signal does not work

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. 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.

  2. 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.

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

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

like image 640
Wei An Avatar asked May 27 '11 14:05

Wei An


1 Answers

You're not setting the sender class for one.

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)

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.

like image 128
Eric Palakovich Carr Avatar answered Sep 22 '22 18:09

Eric Palakovich Carr