views:

119

answers:

2

I have just started implementing signal listeners in a django project. While I understand what they are and how to use them. I am having a hard time figuring out where I should put them. The documentation from the django site has this to say:

Where should this code live?

You can put signal handling and registration code anywhere you like. However, you'll need to make sure that the module it's in gets imported early on so that the signal handling gets registered before any signals need to be sent. This makes your app's models.py a good place to put registration of signal handlers.

While its a good suggestion, having non model classes or methods in my models.py just rubs me the wrong way.

So then, what is the best practice/rule for storing and registering signal handlers?

+1  A: 

I just recently read this article about best practices when it comes to lay out your projects/applications, and it suggests that all your custom dispatcher signals should go in a file called signals.py. However, that doesn't fully solve your problem, since you still need to import these somewhere, and the earlier they get imported the better.

The model suggestion is a good one. Since you already defined everything in your signals.py file, it shouldn't take more than a line at the top of the the file. This is similar to the way the admin.py file is laid out (with class definitions at the top and the code for registering all the custom admin classes at the bottom), if you define your signals then connect them in the same file.

Hope that helps! Ultimately it comes down to what you prefer.

hora
+3  A: 

I actually like to make them classmethods of the model itself. That keeps everything within one class, and means you don't have to worry about importing anything.

Daniel Roseman
I like that. Thanks!
Jason Webb