Django Signals Django.How

Author avatar wrote on 08/06/2022

Signals allow certain senders to notify a set of receivers that some action has taken place so they continue
List is here https://docs.djangoproject.com/en/4.0/ref/signals/


Actions :
    model's save() method is called.
    django.db.models.signals.pre_save | post_save

    model's delete() method is called.
    django.db.models.signals.pre_delete | post_delete

    ManyToManyField on a model is changed.
    django.db.models.signals.m2m_changed

    Django starts or finishes an HTTP request.
    django.core.signals.request_started | request_finished

    pre_save/post_save – this Signal is used before and after the save() method.
    pre_delete/post_delete -this Signal is triggered before and after a model’s instance is deleted (method delete()).
    pre_init/post_init – this Signal is triggered before/after the init(,) method instantiates a model.

Using signals connect


from django.db import models
from django.db.models import signals

def create_customer(sender, instance, created, **kwargs):
    print "Save is called"

class Customer(models.Model):
    name = models.CharField(max_length=16)
    description = models.CharField(max_length=32)

signals.post_save.connect(receiver=create_customer, sender=Customer)

Using receiver


from django.db import models
from django.db.models import signals
from django.dispatch import receiver

class Customer(models.Model):
    name = models.CharField(max_length=16)
    description = models.CharField(max_length=32)

@receiver(signals.pre_save, sender=Customer)
def create_customer(sender, instance, created, **kwargs):
    print "customer created"

Another example


@receiver(post_save, sender=File)
def set_file_attributes(sender, instance, created, **kwargs):
    if created: 
        new_profile = Profile.objects.create(user=instance)
        new_profile.create_auth_token()
        new_profile.save()