Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 77 ยท Middleware, Signals and Internals

Signals

Learn Django signals: connect receivers to pre_save, post_save and m2m_changed, define custom signals, and know when explicit code is the better choice.

Signals let one part of a program announce that something happened, while other parts listen and react, without the two parts knowing about each other. Django uses them internally: saving a model sends pre_save and post_save, deleting sends post_delete, and a request starting sends request_started. You can listen to those, or define signals of your own.

Signals are a tool with a sharp edge. They are great for reacting to events in code you do not own (such as the built-in User model) and for decoupling reusable apps. They are a poor way to organize your own business logic, because they hide the flow of a program. This lesson teaches the mechanics first and then spends time on when to say no.

Senders, signals and receivers

Three words cover the whole system:

  • A signal is an object, such as post_save.
  • A receiver is a function that is called when the signal fires.
  • A sender is who fired it. For model signals the sender is the model class, so a receiver can listen to one model only.
flowchart LR
    M["Article.save()"] -->|"sends post_save"| S(("post_save<br/>signal"))
    S --> R1["receiver: write audit log"]
    S --> R2["receiver: update counter"]

The code that saves an article does not know which receivers exist; each receiver is called with the instance.

The usual way to register a receiver is the @receiver decorator. It takes the signal and, optionally, the sender:

Python
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Article)
def article_saved(sender, instance, created, **kwargs):
    ...

Always accept **kwargs. Django passes several arguments and may add more in the future, so a receiver without **kwargs can break after an upgrade.

Saving and deleting

The next example listens to pre_save, post_save and post_delete for an Article model. Watch the created flag: it is True for an insert and False for an update.

Python pre_save, post_save and post_delete

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two surprises are worth remembering from that output:

  1. pre_save runs before the row is written, so it can change the instance. That is why the slug was filled in without touching the view code. post_save runs after the write, which is when instance.pk exists for a new row.
  2. QuerySet.update() and bulk_create() printed nothing. Those methods write straight to the database without calling save(), so no model signals fire. Any logic you hang on post_save silently skips them.

That second point is a major reason to be careful with signals: whether your code runs depends on how someone changed the data.

Many-to-many changes

Adding to a many-to-many relation does not call save() on either object; it inserts into a hidden join table. To react, use m2m_changed, which has an action argument: pre_add, post_add, pre_remove, post_remove, pre_clear and post_clear. The pk_set argument holds the ids that were added or removed (it is None for clears).

Custom signals

You can create your own signal by making a Signal object and calling send() when the event happens. Use this when your app wants to offer an extension point to other apps, for example "an order was paid".

Python m2m_changed and a custom signal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A few details from the custom signal part:

  • send() calls every receiver and returns a list of (receiver, response) pairs. If a receiver raises, the exception propagates and the remaining receivers do not run.
  • send_robust() catches exceptions and returns them in the list, so one broken listener cannot stop the others.
  • dispatch_uid is a unique string that stops a receiver from being connected twice, which can otherwise happen if the module that connects it is imported under two names.
  • Receivers are called synchronously, in the same thread, before send() returns. A slow receiver slows the code that fired the signal.

Where to connect receivers in a real project

In a real project, put receivers in a signals.py file inside your app and import it from the app's ready() method, so they are connected exactly once when Django starts:

Python
# blog/apps.py
from django.apps import AppConfig


class BlogConfig(AppConfig):
    name = "blog"

    def ready(self):
        from . import signals  # noqa: F401  (importing connects the receivers)

If you forget this step, the receivers are never imported and nothing happens, which is a common reason for "my signal does not fire". You can learn more about app configuration in Projects, Apps and Settings.

When not to use signals

Signals tempt you because they feel tidy: "when an order is saved, send an email". But consider the downsides:

  • Hidden flow. Reading order.save() tells you nothing about the email, the stock update and the audit entry that happen as a result. Debugging means searching the project for receivers.
  • Skipped paths. As you saw, update(), bulk_create() and raw SQL bypass them.
  • Ordering and transactions. Receivers run inside the caller's transaction. If you send an email in post_save and the transaction later rolls back, the customer got an email for an order that does not exist. The fix is transaction.on_commit(...), covered in Transactions and Concurrency.
  • Testing. Every test that saves the model triggers every receiver.

A good rule: if the code that triggers the effect and the code that performs it are in the same app, call the function directly (in a model method or a service function). Use signals when the sender genuinely should not know about the listener, for example a reusable app reacting to the User model, or an extension point you offer to other apps.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which method call does NOT trigger post_save?

    QuerySet.update() writes directly to the database without calling save(), so model signals such as pre_save and post_save are not sent. The other calls all go through save().
  2. 2. What does the 'created' argument of a post_save receiver tell you?

    created is True for an INSERT and False for an UPDATE of an existing row.
  3. 3. Why should a receiver function accept **kwargs?

    Signals call receivers with keyword arguments. Accepting **kwargs keeps the receiver working when Django adds new arguments.
  4. 4. Which is the best reason to avoid a signal and call a function directly?

    When both sides are under your control, an explicit call is easier to read, test and trace. Signals suit decoupled or third-party code.
  5. 5. Where should you import the module that connects your receivers in a real project?

    ready() runs once when Django starts, so importing signals there connects each receiver exactly once.

Summary

  • A signal announces an event; receivers registered with @receiver react, and for model signals the sender is the model class.
  • Always accept **kwargs in receivers; use created in post_save to tell inserts from updates.
  • pre_save can still change the instance; post_save sees the saved row with its primary key.
  • update(), bulk_create() and raw SQL do not send save() signals; many-to-many changes use m2m_changed with an action.
  • Custom signals use Signal(), connect(), send() and send_robust(); dispatch_uid prevents double registration.
  • Connect receivers from AppConfig.ready(), and prefer plain function calls when both sides are in your own code.

Next lesson: Custom Management Commands.