Saturday, 2 June 2018

Django m2m_changed signal is never called

I can't understand why my m2m_changed signal is not triggered, while a request_finished signal works correctly.

Here is the code:

models.py

class Badge(TimeStampable, Expirable, Deactivable,
            SafeDeleteModel):
    _safedelete_policy = HARD_DELETE

    owner = models.ForeignKey(settings.AUTH_USER_MODEL,
                              blank=True, null=True,
                              on_delete=models.PROTECT)
    restaurants = models.ManyToManyField(Restaurant)
    identifier = models.CharField(max_length=2048)

    objects = SafeDeleteManager.from_queryset(BadgeQuerySet)()

signals.py

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

from .models import Badge

@receiver(m2m_changed, sender=Badge.restaurants.through)
def my_callback(sender, **kwargs):
    print("M2M has been changed!")

@receiver(request_finished)
def other_callback(sender, **kwargs):
    print("Request finished!")

apps.py (this post advised to change this file)

from django.apps import AppConfig

class BadgesConfig(AppConfig):
    name = 'badges'

    def ready(self):
        import badges.signals

When going to a shell:

  • request_finished.receivers returns a non-empty list (it works)
  • m2m_changed.receivers returns an empty list (it does not work, and the signal can never be received)

I found similar post but did not found the answer in it.

Why m2m_changed signal does not work?



from Django m2m_changed signal is never called

No comments:

Post a Comment