Category: django

Don’t use string literals for sender values in Django’s signal dispatcher

Posted by – August 8, 2011

TL; DR Don’t use a string literal as the value of the sender attribute when defining your own Django signals.

I got bit by a nasty bug today using Django’s signal framework. I used the signal like so:

show_user_widget_responses = show_user_widget.send(
    sender='my_widget_view',
    user=user
)

I ran the tests to make sure the signal was being sent to the listeners (i.e receivers) and they all passed. I then noticed the view sent another signal in certain conditions and its sender was a set to a different string. For the sake of consistency, I changed the above signal’s sender string to “widget-user-view” and went to make a cup of tea.

When I returned to my desk, I got a bit distracted and continued to work on the feature. I ran the app’s tests and they started failing: the test listeners weren’t being called. Oops.

More