Where to put django signal receiver code?

Viewed 2356

Hi I am defining my own signal and receiver. I just want to know where I should place my codes. It is in models.py or in views.py. Please help

4 Answers

Put your signal function into signals.py and don't forget to put the app config in the __init__.py file and also ready method in the apps.py file.

apps.py:

from django.apps import AppConfig


class AppNameConfig(AppConfig):
    name = 'app_name'

    def ready(self):
        import app_name.signals

__init__.py (app folder):

default_app_config = 'app_name.apps.AppNameConfig'

You can create signals.py file. But can not add import signals to __init__.py file. Because signal related models will not be loaded yet. So, in apps.py file you can find class which inherit from AppConfig class and this class has method ready(self) method. You should import your signals in this function:

from django.apps import AppConfig


class MainConfig(AppConfig):
    name = 'main'

    def ready(self):
        import main.signals

Given an app called "app" to handle the pre_save signal of a model called "Model"

apps.py

from django import apps
from django.db.models import signals
class AppConfig(apps.AppConfig):
    name = 'app'
    def ready(self):
        # import here to avoid circular imports
        from app import signals as app_signals
        signals.pre_save.connect(app_signals.model_pre_save, sender=self.get_model('Model'))

signals.py

def model_pre_save(sender, instance, **kwargs):
    if kwargs.get('raw', False):
        return  # raw implies fixture, ignore
    # add code here to handle signal
Related