5

I've put my signal receiver code in the respective model file.

However, signal receivers keep growing and I'd like to separate them over multiple files.

I haven't seen discussion on where to put signal receiver codes.

(makes me suspect that I'm not supposed to make many signal receivers maybe?)

eugene
  • 39,839
  • 68
  • 255
  • 489

1 Answers1

11

See the docs:
https://docs.djangoproject.com/en/1.8/topics/signals/#connecting-receiver-functions

it's common to put them in a separate signals.py file, perhaps one per module in your project, but you need to ensure that these files get imported so that your signal receivers get registered.

as detailed in the docs above, Django 1.7+ now has the AppConfig.ready mechanism for this kind of case

There's a good explanation here:
http://chriskief.com/2014/02/28/django-1-7-signals-appconfig/

(as an example of what you might do)

basically:

# myapp/__init__.py
default_app_config = 'myapp.apps.MyAppConfig'

and

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

class MyAppConfig(AppConfig):

    name = 'myapp'
    verbose_name = 'My App'

    def ready(self):

        # import signal handlers
        import myapp.signals.handlers
Anentropic
  • 32,188
  • 12
  • 99
  • 147
  • oh I mean, signal receivers, not the signal itself. – eugene Apr 17 '15 at 11:58
  • the answer is the same – Anentropic Apr 17 '15 at 11:59
  • so it's customary to put signal receivers in `signals.py` ? or `AppConfig.ready` part is applicable to signal receivers as well as signals? – eugene Apr 17 '15 at 12:25
  • 3
    It should be noted that as of 1.8, the Django docs say "New applications should avoid default_app_config. Instead they should require the dotted path to the appropriate AppConfig subclass to be configured explicitly in INSTALLED_APPS." Thus, you just put `myapp.apps.MyAppConfig` directly in to `INSTALLED_APPS` instead of using the `default_app_config` when you're creating a new application. – Dustin Wyatt Nov 23 '15 at 20:24