Working Ninja
2017-11-18T10:17:05
Django Signals

This post outlines that bare minimum that needs to be done to set up a post_save signal using Django. One rationale behind using a signal is that a model instance can be saved without the user having to wait for additional code to process (e.g. consuming an external API). This lets the user quickly save a form and be on their merry way while in the background the model save() method triggers our signal which executes additional code. This all happens without incuring any wait time for the user.

Create a new file to hold our signals:

# polls/signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Polls


@receiver(post_save, sender=Polls)
def email_poll_author(sender, **kwargs):
    # Code to email poll author

""" https://docs.djangoproject.com/en/stable/topics/signals/#connecting-to-signals-sent-by-specific-senders """

Initialize our signals when Django loads:

# polls/apps.py
from django.apps import AppConfig


class PollsConfig(AppConfig):
    def ready(self):
        from . import signals

""" https://docs.djangoproject.com/en/stable/ref/applications/#django.apps.AppConfig.ready """

Lastly, tell Django to use our AppConfig (polls/apps.py):

# polls/__init__.py
default_app_config = 'polls.apps.PollsConfig'

""" https://docs.djangoproject.com/en/stable/ref/applications/#for-application-authors """

Signals: https://docs.djangoproject.com/en/stable/topics/signals/
Additional types of signals: https://docs.djangoproject.com/en/stable/ref/signals/