liveBook · Manning

Receiver decorator

As explained in Django in Action

The Django receiver decorator registers a callable as a handler for a signal from a specified sender.

The Django receiver decorator registers a callable as a handler for a signal from a specified sender. Think of it as wiring an event alarm: when the sender performs an action, Django calls the handler. section 6.5

Create a profile after a user is saved

@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) Here, the decorator connects User to post_save. The handler creates a UserProfile only for a newly created User that was not loaded from a fixture, while avoiding duplicates. section 6.5

A receiver handler typically accounts for these signal details:

  • Use the sender argument to identify the model whose action triggered the signal. section 6.5
  • Accept **kwargs because signals can provide additional values such as created, raw, and instance. section 6.5
  • Distinguish first saves from updates because Django provides save signals, not a separate create signal. section 6.5

How Django in Action covers it

How deep it goes
Explains registration, handler arguments, save timing, fixture handling, and duplicate prevention through a worked implementation.
Examples
Demonstrates automatic UserProfile creation when a User is newly saved outside fixture loading.
What it assumes
Assumes familiarity with Django models and UserProfile while explaining signal arguments and registration directly.
What you can do after
Build it from scratch by registering a post_save handler and conditionally creating a related model instance.
How it connects
Connects signals, senders, signal handlers, post_save, Django models, fixtures, and UserProfile creation.

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.