Full answer
Signals decouple senders from receivers, but they hide control flow. Use them for cross-app notifications where the sender should not know the listeners; use plain function calls when you own both sides.
Custom signal:
fee_paid = Signal() # Django 3.0+ takes no providing_args
fee_paid.send(sender=Fee, instance=fee, amount=500)
@receiver(fee_paid, dispatch_uid="send_receipt_v1")
def send_receipt(sender, instance, amount, **kwargs): ...Pitfalls:
- Duplicate registration: if the module that registers the receiver is imported under two names, or
ready()runs twice in tests, the receiver is called twice.dispatch_uidmakes the pair (signal, uid) unique. - Weak references:
connect()stores receivers weakly by default. A lambda or nested function is garbage-collected right away and never fires. Use module-level functions, orweak=False. - Exceptions:
send()stops at the first receiver exception and re-raises it, so one bad listener breaks the sender.send_robust()catches exceptions, returns[(receiver, response_or_exception)], and you should log failures. - Order: receivers run in connection order, which depends on import order. Do not rely on it.
- Transactions:
post_saveruns inside the open transaction. If it sends an email or queues a task and the transaction later rolls back, the side effect already happened. Wrap external effects intransaction.on_commit(). - Bulk operations:
bulk_create,update()andQuerySet.delete()fast paths skip many signals (post_save), so signals are not a complete audit mechanism. - Registration location: connect receivers in
AppConfig.ready()so they are imported once at startup. - Performance: each signal adds calls on hot paths; filter early with
sender=.
Alternatives: explicit service functions, model save() overrides for logic that is truly part of the model, and an outbox table for reliable events.
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
import gc
from django.db import models, connection, transaction
from django.db.models.signals import post_save
from django.dispatch import Signal, receiver
fee_paid = Signal()
log = []
def receipt(sender, **kwargs):
log.append("receipt")
def broken(sender, **kwargs):
raise RuntimeError("mail server down")
def ledger(sender, **kwargs):
log.append("ledger")
fee_paid.connect(receipt, dispatch_uid="receipt_v1")
fee_paid.connect(receipt, dispatch_uid="receipt_v1") # duplicate import: ignored
fee_paid.connect(broken, dispatch_uid="broken_v1")
fee_paid.connect(ledger, dispatch_uid="ledger_v1")
print("receivers:", len(fee_paid.receivers))
try:
fee_paid.send(sender="Fee")
except RuntimeError as exc:
print("send() raised:", exc, "| log:", log)
log.clear()
results = fee_paid.send_robust(sender="Fee")
print("send_robust log:", log, "| errors:", [type(r).__name__ for _, r in results if isinstance(r, Exception)])
fee_paid.connect(lambda sender, **kw: log.append("lambda"), dispatch_uid="lam") # weak reference to a temporary
gc.collect()
log.clear()
fee_paid.send_robust(sender="Fee")
print("lambda fired:", "lambda" in log)
class Fee(models.Model):
amount = models.IntegerField()
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Fee)
emails = []
@receiver(post_save, sender=Fee, dispatch_uid="email_on_save")
def email_receipt(sender, instance, created, **kwargs):
emails.append(f"sent immediately for {instance.amount}") # fires before commit
transaction.on_commit(lambda: emails.append(f"sent after commit for {instance.amount}"))
try:
with transaction.atomic():
Fee.objects.create(amount=500)
raise RuntimeError("payment gateway failed")
except RuntimeError:
pass
print(Fee.objects.count(), emails)
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. In a test run on_commit callbacks are discarded by TestCase unless captured; here autocommit mode is used outside the failing atomic block. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): receivers: 3 send() raised: mail server down | log: ['receipt'] send_robust log: ['receipt', 'ledger'] | errors: ['RuntimeError'] lambda fired: False 0 ['sent immediately for 500']
Key points
- send() is synchronous and stops on the first exception; send_robust() collects them
- dispatch_uid prevents duplicate receivers
- Receivers are weak references by default
- post_save fires inside the transaction; use on_commit for side effects
- Bulk operations skip many signals
Common mistakes
- Registering receivers inside functions or with lambdas and losing them to garbage collection
- Sending emails or tasks from post_save inside a transaction
- Relying on receiver order or on signals for bulk operations
- Letting one failing receiver break the sender without choosing send_robust
Follow-ups
- When would you replace signals with an explicit service call?
- Where should receivers be connected, and why?
- What do pre_save and post_save get as arguments?
Tips
- List 4 pitfalls
- Say on_commit for side effects
- Differentiate send and send_robust