9

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

9
  • 2
    Mostly in models.py, but if you want you can put that in separate file like signal_handlers.py
    – Rohan
    Aug 11, 2012 at 6:22
  • I was able to find out. I Placed my objects in models.py and imported them in views where I used the sender function
    – flexxxit
    Aug 11, 2012 at 7:00
  • You Know I tried defining my own sigs.py but the function call was not working. Can U help me out. i would really like to tidy up my code
    – flexxxit
    Aug 11, 2012 at 7:05
  • Could you update your question with relevant error details.
    – Rohan
    Aug 11, 2012 at 7:40
  • I created the signals_handlers.py and it works fine. thanks
    – flexxxit
    Aug 11, 2012 at 7:43

4 Answers 4

4

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'
0
  1. Create python file - signals.py in your application.
  2. Add this line in __init__.py in your application.

    import signals

  3. Restart django project.

Work it!

0

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
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.