liveBook · Manning

Django signal

As explained in Django in Action

A Django signal is an event-notification mechanism that allows registered receivers to respond when specified framework or application events occur.

A Django signal lets one part of an application react when a framework or application event occurs. It follows the observer/observable pattern: register interest in an action, then receive a notification when that action happens. Signals are especially useful with the Django ORM, such as creating a UserProfile automatically after a User is created. section 6.5

Use a signal by connecting a receiver to the relevant event and sender:

  • Choose the signal. ORM actions commonly provide pre and post signals, such as pre_save and post_save. section 6.5
  • Choose the sender, such as the User model whose action should trigger the receiver. section 6.5
  • Register a handler with Django’s @receiver decorator. section 6.5
  • Inspect the event details in the handler. For a post_save handler, created identifies a newly created object and raw identifies fixture loading. section 6.5

Create a profile after user creation

A receiver for post_save on User can check kwargs['created'] and not kwargs['raw'], obtain kwargs['instance'], verify that a UserProfile does not already exist, and create one when necessary. This guards against missing profiles and avoids duplicating a profile if the admin created one first. A pre signal can also affect whether an action proceeds; a handler’s return value for pre_save indicates whether saving should take place. section 6.5

Figure 6.5 Registering and handling a signal from a Model
figure

Trace the relationship between a model action, the signal registry, and the registered signal handler. section 6.5

How Django in Action covers it

How deep it goes
Explains observer registration, senders, pre/post timing, handler arguments, and duplicate protection without detailing signal dispatch internals.
Examples
Uses automatic UserProfile creation, admin-created profiles, fixture loading, and failed-login capture as practical signal examples.
What it assumes
Assumes familiarity with Django models and users while teaching signal registration and event-handler arguments through the profile example.
What you can do after
Build it from scratch by registering a receiver that performs a guarded side effect after a Django model event.
How it connects
Connects the observer/observable pattern with Django ORM models, User, UserProfile, post_save, pre_save, and receiver functions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.