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
Trace the relationship between a model action, the signal registry, and the registered signal handler. section 6.5
