django signals instance code example

Example 1: django builtin signals

django post_save signals

Let’s have a look on the post_save built-in signal. Its code lives in the django.db.models.signals module. This particular signal fires right after a model finish executing its save method.

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

def save_profile(sender, instance, **kwargs):
    instance.profile.save()

post_save.connect(save_profile, sender=User)

Another way to register a signal, is by using the @receiver decorator:
 
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

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

Example 2: django builtin signals

django built-in signals 

Django's built-in Signals:
Django provides a set of built-in signals that let user code get notified by Django itself of certain actions. These include some useful notifications:

django.db.models.signals.pre_save & django.db.models.signals.post_save : Sent before or after a model's save() method is called
django.db.models.signals.pre_delete & django.db.models.signals.post_delete : Sent before or after a model's delete() method or queryset's delete() method is called
django.db.models.signals.m2m_changed : Sent when a ManyToManyField on a model is changed
django.core.signals.request_started & django.core.signals.request_finished : Sent when Django starts or finishes an HTTP request