liveBook · Manning

Signal handler

As explained in Django in Action

A signal handler is a callable that receives a signal notification and performs corresponding application logic.

A signal handler is a callable that reacts when Django reports an event, then performs application logic as a side effect. Signals follow the observer/observable pattern: register interest in an action, and Django calls the handler when that action occurs. ORM actions commonly provide pre and post signals; a post signal runs after the action has happened. section 6.5

A practical use is keeping every User paired with a UserProfile. Register the handler for post_save, because the profile should be created after the User exists. The handler receives the sending model through sender and should accept **kwargs because signals can provide additional parameters. section 6.5

A robust User post-save handler follows this flow:

  • Check kwargs['created'] so updates do not create a second profile. section 6.5
  • Check kwargs['raw'] so fixture loading does not trigger normal profile creation. section 6.5
  • Read kwargs['instance'] to obtain the newly saved User. section 6.5
  • Verify that a UserProfile does not already exist, then create one when necessary. section 6.5

Creating a profile after User creation

@receiver(post_save, sender=User) def user_post_save(sender, **kwargs): if kwargs['created'] and not kwargs['raw']: user = kwargs['instance'] try: UserProfile.objects.get(user=user) except UserProfile.DoesNotExist: UserProfile.objects.create(user=user) The receiver connects User actions to post_save. A newly created User that was not loaded from a fixture gets a profile, while an existing profile is left alone.

How Django in Action covers it

How deep it goes
Explains observer registration, pre/post timing, receiver arguments, fixture handling, duplicate checks, and ORM creation.
Examples
Demonstrates a User post-save receiver that creates a missing UserProfile and verifies the resulting relation.
What it assumes
Uses Django User models, ORM saves, fixtures, and model relationships as the surrounding application concepts.
What you can do after
Build it from scratch by registering a post_save receiver that safely creates related profiles.
How it connects
Connects the observer/observable pattern, Django ORM actions, post_save, User, UserProfile, and fixtures.

Also explained in

Compare how 4 books explain signal handler →

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.