4

I am trying to use the m2m_changed signal to trigger some actions in my application . However, the printout of signaltest() indicates that I am only signalled on pre_clear and post_clear actions. My models.py looks like this:

class Entry(models.Model):
    objects = managers.MyEntryManager()
    ...
    fields = models.ManyToManyField('Field', through='EntryField')

class Field(models.Model):
    name = models.CharField(max_length=64, unique=True)
    description = models.CharField(max_length=256, blank=True)

class EntryField(models.Model):
    entry = models.ForeignKey('Entry')
    field = models.ForeignKey('Field')
    value = models.CharField(max_length=256)

def signaltest(**kwargs):
    print kwargs['action']
signals.m2m_changed.connect(signaltest, sender=Entry.fields.through, weak=False, dispatch_uid='signaltest')

The EntryField objects are created elsewhere in the code using the following code:

some_entry.fields.clear()
models.EntryField.objects.get_or_create(
    entry=some_entry,
    field=some_field,
    defaults = { 'value': field_value }
)

The first call is responsible for the pre_clear and post_clear events I receive. However, the second call generates no signals.

It seems to me that django bug #13757 is related to this (mis)behaviour, but I may be missing something.

Is there a way to "rewire" the signals (perhaps using some signal other than m2m_changed) to have post_save signals generated when a EntryField is created?

m000
  • 5,932
  • 3
  • 31
  • 28
  • 3
    Is there some reason you don't connect your signal handler to post_save? – Chris Lawlor Oct 07 '12 at 13:36
  • `m2m_changed` just looked more suitable. I wouldn't mind using `post_save` signal if I had an explanation for the following behaviour: I get a `TypeError: 'str' object is not callable` when connecting to `post_save` and printing `kwargs`. The error is generated at the time `kwargs['instance']` is printed. Curiously, if I just use `kwargs['instance']` without printing it, there are no problems. This makes me a bit sceptical on whether `post_save` should be used in this way. – m000 Oct 14 '12 at 21:22
  • @ChrisLawlor Ok. I solved the `TypeError` issue. It was my fault after all - had missed a `%` in the implementation of `EntryField.__unicode__` (not shown above). Thanks! – m000 Oct 15 '12 at 08:01

1 Answers1

0

could you please try this out?

def signaltest(**kwargs):
   print kwargs['instance']
   print kwargs['created']

signals.post_save.connect(signaltest, sender=EntryField, weak=False, dispatch_uid='signaltest')
dnozay
  • 23,846
  • 6
  • 82
  • 104
  • The `action` argument is specific to `m2m_changed` signal. So, your snippet (which connects to `post_save` signal) throws an exception. Are you sure you haven't mistyped anything? – m000 Oct 14 '12 at 20:50