0 day streak
python / beginner
Snippet

Decoupled Logic with Signals

Signals allow you to execute code when a specific action happens elsewhere in your application, such as saving a user.

snippet.py
python
1
2
3
4
5
6
7
8
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
@receiver(post_save, sender=User)
def user_created_handler(sender, instance, created, **kwargs):
if created:
print(f'New user: {instance.username}')
django
Breakdown
1
@receiver(post_save, sender=User)
Connects this function to the 'post_save' signal of the User model.
2
if created:
A boolean that is True if a new record was created, False if updated.
3
instance
The actual object instance that was just saved.