Code


Version 5 (modified by Tyson Tate <tyson@…>, 8 years ago) (diff)

Fixed wiki-words

What Are Signals?

Signals allow you to make Django call custom methods after common actions using a dispatcher. Beyond that, I really don't know much else. Please help expand this documentation, if you can.

The author of Zyons talks about signals a bit here.

Built-In Signals

Django has the following build in signalers:

  • class_prepared
  • pre_init
  • post_init
  • pre_save
  • post_save
  • pre_delete
  • post_delete
  • post_syncdb

All the above are related to classes in your models.py files.

Custom Signals

You can send custom signals from the dispatcher, as well. In the following example from this intro to signals, a signal called "object_viewed" is sent whenever the following bit is called:

dispatcher.send(signal=signals.object_viewed, request=request, object=object)

You'll have to instantiate the signal in a file called "signals.py" in your app's folder:

object_viewed=object()

And then, in any file in which you use that signal (typically, models.py and views.py), you'll need to import your signals file:

from project.app import signals

Example

The following is taken from Zyons, the only place I've seen signals used so far. Unless I'm completely incorrect, the following code has the dispatcher call "increment_tag_summary" before a TagUserObject object is saved, and "decrement_tag_summary" after a TagUserObject object is deleted.

models.py

from django.db.models import signals
from django.dispatch import dispatcher

[...]

def increment_tag_summary(sender, instance, signal, *args, **kwargs):
    [...]

def decrement_tag_summary(sender, instance, signal, *args, **kwargs):
    [...]

dispatcher.connect( increment_tag_summary , signal=signals.pre_save, sender=TagUserObject )
dispatcher.connect( decrement_tag_summary , signal=signals.post_delete, sender=TagUserObject )