I am using django 2.0.8 and Python 3.5. I want to be able to send and receive custom signals when an object is saved to the database.
I have followed the Django documentation on listening to signals and also the core signals bundled with Django - however, I am unable to get my example to work.
This is what I have so far:
myapp/models.py
from django.db import models
import django.dispatch
my_signal = django.dispatch.Signal(providing_args=["name"])
class Foo(models.Model):
name = models.CharField(max_length=16)
def save(self, *args, **kwargs):
try:
# Call the "real" save() method.
super().save(*args, **kwargs)
# Fire off signal
my_signal.send(sender=self.__class__, name=self.name)
except Exception as e:
print ('Exception:', e)
#pass
myapp/signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Foo
@receiver(post_save, sender=Foo)
def foo_handler(sender, **kwargs):
print('Foo Signal Recieved!')
print(kwargs)
myapp/app.py
class MyappConfig(AppConfig):
name = 'myapp'
label = 'myapp'
def ready(self):
import myapp.signals
Sample usage
from myapp.models import Foo
foo = Foo(name='Homer Simpson')
foo.save() # Object is saved, but event is not fired!
Can anyone explain why the signal is not being fired?
print('signal received')
in your code to check that it's called? – Symphysismanage.py dumpdata
(docs.djangoproject.com/en/2.0/howto/initial-data/…) to get a dump that you can then modify. – Symphysisfooch_save
when you update the tableFoodooChile
? You should add logging to that function and runFoodooChile.objects.create(name='test')
in the shell – Sisterpython manage.py shell
, you need import the signal.py first .otherwise, signal won't work. – Mahounddefault_app_config
in your myapp/__init__.py file? default_app_config – MahoundINSTALLED_APPS
fromsettings.py
, specifically the part where you includemyapp
. – Tarpan