python / beginner
Snippet
Decoupling Logic with Signals
Django signals allow certain senders to notify a set of receivers when actions occur, such as creating a profile automatically when a user is saved.
snippet.py
1
2
3
4
5
6
7
8
from django.db.models.signals import post_savefrom django.dispatch import receiverfrom .models import Profile, User@receiver(post_save, sender=User)def create_user_profile(sender, instance, created, **kwargs):if created:Profile.objects.create(user=instance)
django
Breakdown
1
@receiver(post_save, sender=User)
Connects the function to the signal emitted after a User model is saved.
2
if created:
A boolean that is True if a new record was created, and False if an existing one was updated.