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.



