0

I'm trying to create a hook for when i made a new save() on some model and for a reason that i don't understand the receiver method is not called if the decorated method is in another file.

I've a class called Pizza and i want to use the pre_save method from django.db.models.signals to perform a action before the content is saved

# models.py file
class Pizza(models.Model):
    name = models.CharField(max_length=200)
# actions.py file
from .models import Pizza
from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=Pizza)
def before_action(instance, **kwargs):
    logger.info("Before action method was called.")

The code above doesn't work unless i put the method before_action within the Pizza model like this:

# models.py file

from django.db.models.signals import pre_save
from django.dispatch import receiver

class Pizza(models.Model):
    name = models.CharField(max_length=200)

@receiver(pre_save, sender=Pizza)
def before_action(instance, **kwargs):
    logger.info("Before action method was called.")

How can i split this 2 responsibilities on each file? i would like to keep all actions in a separated file

I've also tried to follow this answer but it didn't work: https://stackoverflow.com/a/8022315/2336081

Rafa Acioly
  • 530
  • 9
  • 34

1 Answers1

2

It looks like you need to import the signals.

my_app/apps.py

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'my_app'

    def ready(self):
        import my_app.signals

my_app/__init__.py

default_app_config = 'my_app.apps.MyAppConfig'

Replacing my_app with the correct value. Check this answer for more information.

Soviut
  • 88,194
  • 49
  • 192
  • 260
gdef_
  • 1,888
  • 9
  • 17