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
