Django signals

This is a really cool feature of django that I’ve never explored, so I though I’d made a post about it so to remind myself of using it more often! It’s discussed extensively in the docs here and here. In a nutshell:

Django includes a “signal dispatcher” which helps allow decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place. They’re especially useful when many pieces of code may be interested in the same events.

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 is called.
django.core.signals.request_started & django.core.signals.request_finished
Sent when Django starts or finishes an HTTP request.

How to use them?

Really simple: modify the code below as needed and put it at the bottom of your models.py file (it could be located anywhere, but by putting it there we make sure it’s loaded at the right time):

from django.db.models.signals import post_save

def my_handler(sender, instance, created, **kwargs):
    if created:
        # if the instance is effectively saved
        try:
            if instance.my_favourite_method():
                instance.special_field = instance.my_favourite_method()
        except:
            instance.special_field = "undefined"
        instance.save()


post_save.connect(my_handler, sender=SomeModel)

Imagine that each time an instance of SomeModel gets saved you want to perform some other operation, such as adding something to one of its fields. Three simple steps: import the post_save signal, define a function my_handler that does the operation, connect your handler to a specific model.

 

Share/Bookmark






Comments are closed.