Django - signals. Simple examples to start
You can find very good content about django signals over Internet by doing very small research.
Here i will explain you very brief about Django signals.
What are Django signals?
Signals allow certain senders to notify a set of receivers that some action has taken place
Actions :
model's save() method is called.
django.db.models.signals.pre_save | post_save
model's delete() method is called.
django.db.models.signals.pre_delete | post_delete
ManyToManyField on a model is changed.
django.db.models.signals.m2m_changed
Django starts or finishes an HTTP request.
django.core.signals.request_started | request_finished
All signals are django.dispatch.Signal instances.
very basic example :
models.py
from django.db import modelsfrom django.db.models import signalsdef create_customer(sender, instance, created, **kwargs): print "Save is called"class Customer(models.Model): name = models.CharField(max_length=16) description = models.CharField(max_length=32)signals.post_save.connect(receiver=create_customer, sender=Customer)
Shell
In [1]: obj = Customer(name='foo', description='foo in detail')In [2]: obj.save()Save is called
Apart from the explanation given by Prashant, you can also use receiver decorator present in django.dispatch
module.
e.g.
from django.db import modelsfrom django.db.models import signalsfrom django.dispatch import receiverclass Customer(models.Model): name = models.CharField(max_length=16) description = models.CharField(max_length=32)@receiver(signals.pre_save, sender=Customer)def create_customer(sender, instance, created, **kwargs): print "customer created"
For more information, refer to this link.
In the signals.post_save.connect(receiver=create_customer, sender=Customer)... sender will always be the model which we are defining... or we can use the User as well in the sender.