Django Signals Example

Recently I have gotten serious about writing modular, re-usable Django apps, which has lead me to Django signals. In the past, I have avoided signals based on the ideas in “Two Scoops of Django“. Their point is that often Django noobs resort to signals, when there are simpler solutions such as over-riding model save methods. If you look at the questions on Stackoverflow related to Django signals, you will see that the “Two Scoops” advice is wise.

However, when it comes to modular apps, signals are the ideal way to let one module do something when something happens in another module. In my case, I needed a module to do something when a model was saved in another module. Here is how I did it.

Module1 models.py

No changes required. Django models send signals automagically.

Module 2 Receiver

You can call this file whatever you want. I called mine receivers.py. Here is the code:

# receivers.py

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

from module1.models import AModel

@receiver(post_save, sender=AModel)
def handle_a_model_save(sender, **kwargs):
    print 'signals: a model was saved'

This is were I screwed up (which prompted this blog post), so pay attention. Django learns about your receivers via your apps urls.py file. Something like this:

# urls.py

import receivers  # this is your receivers file
from django.conf.urls import patterns

urlpatterns = patterns('',
    ...your normal urls go here...   
)

That’s it. Just import your receivers file. You do not need to add any new urlpatterns. It’s almost too easy.

I will say it again for the bots: if your Django signals receivers are not working, it may be because you did not add them to your urls file.

2 thoughts on “Django Signals Example

Leave a comment