Django Signals

sjp5554·2020년 7월 20일
0

Sometimes you need to notify decoupled applications when certain events occur. One example could be invalidating a cached page everytime a given model instance is updated. With signals, you can trigger some pieces of code to be executed when some action take place on the model, such as .save().

When using signals, there is a receiver, which is a function or an instance method which receives the signal, and a sender, which is a Python object that sends the signal to the receiver. The connection between the sender and the receiver is done through the connect method provided by Django's "signal dispatchers", which are Signal instances.

Check out the Django documentation for more detail.

Example Usage

Signal can be used when you extend a Django User model with a one-to-one profile model.

profiles/signals.py

from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

from cmdbox.profiles.models import Profile

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

profiles/app.py

from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _

class ProfilesConfig(AppConfig):
    name = 'cmdbox.profiles'
    verbose_name = _('profiles')

    def ready(self):
        import cmdbox.profiles.signals  # noqa

profiles/init.py

default_app_config = 'cmdbox.profiles.apps.ProfilesConfig'

The example above is from this reference.

0개의 댓글