Python – Signals registered more than once in django1.1 testserver

djangodjango-modelsdjango-signalspython

I've defined a signal handler function in my models.py file. At the bottom of that file, I use signals.post_save.connect(myhandler, sender=myclass) as recommended in the docs at http://docs.djangoproject.com/en/dev/topics/signals/.

However, when I run the test server, simple print-statement debugging shows that the models.py file gets imported twice and (as far as I can tell), this causes my signal handler to get registered twice. This means that every action is handled twice, which is obviously not the intended behaviour.

The first import seems to occur during the model checking phase, and the second happens right when the model itself is needed during the first request handled by the server.

Should I be registering my signals handlers elsewhere? Is this a bug in the 1.1 test server? Am I missing something else?

Best Answer

The signature for the connect method is

def connect(self, receiver, sender=None, weak=True, dispatch_uid=None)

where the dispatch_uid parameter is an identifier used to uniquely identify a particular instance of a receiver. This will usually be a string, though it may be anything hashable. If receivers have a dispatch_uid attribute, the receiver will not be added if another receiver already exists with that dispatch_uid.

So, you could specify a dispatch_uid in your connect call to see if that eliminates the problem.

Related Topic