Django 1.11: Signals

One of the best parctices in the world of programming is loose coupling which means when a ClassA depends lighlty on ClassB than the chances or the risks of ClassA being affected by the changes made on ClassB are low, thus this can help isolating problems when things go wrong, simplify testing and maintenance but this can also creates issues in maintaining data synchronization, in general when a developer prioritize loose coupling the chances that he might get stuck in the problem of data synchronization are high.

Solution: Django way !

Django provides what we call Signal Dispatcher which will help or allow decoupled applications within your project get notified when an action occur elsewhere.

So whenever you come across this problem of decoupling signals can simplify thing for you.

Builtin signals

Well the most used signals in Django are those related to the model, at this moment Django has 8 but let’s see the 5 important ones:

  • pre_save(): sent before the model is saved.
  • post_save(): sent after the model is saved.
  • pre_delete(): sent before the model is deleted.
  • post_delete(): sent after the model is deleted.
  • m2m_changed(): sent when a ManyToManyField on a model is changed
Django has other types of signals like signals related to a request, to tests and management. You can read about them by clicking here.

Into the practise

Let’s say you have a blog application where users can post articles so each article belongs to one user and each user can write many articles.

Article Model

To implement this model jump over your models.py file and add these lines of code.

The second thing to do is regestring this model to the admin area, so in admin.py file add also these lines of code.

Now let’s say that we want to add a badge system so each user can have multiple badges and of course a set of predefined badges.

Badge Model

To be able to do that from you badge application add these lines of code into the models.py file.

Signals in action

Let’s say now whenever the user posts his first article we want to give him the author badge, create another file called signals in your badge application.

First we have the send_badge(sender, **kwargs) receiver function, this function will be executed whenever the sender(Article model) gets executed (after the save method).

The @receiver decorator allows you to connect the receiver to the signal(we are using the post_save() signal).

The kwargs[‘instance’] is the Article model itself .

Quick note

Don’t forget to add default_app_config within the __init__.py file of the badge application otherwise the signal won’t work.

default_app_config = 'badges.apps.BadgesConfig'

After the user creates its first Article you can see that a the author badge will be given to him.