0

I'm trying to use signals post_save for the first time. I have read the documents, but still need some advice.

I'm trying to update my model field called 'charge'.

@receiver(post_save, sender=Message)
def my_handler(sender, **kwargs):
    if not sender.charge:
        sender(charge=sender.length(sender))
        sender.save()

However, this gives the error Message' has no attribute 'charge', but charge does exist within message!

MarkO
  • 775
  • 2
  • 12
  • 25
  • 1
    Note that, because `sender` is the `Message` class itself, rather than an instance, your 4th line instantiates a new Message, then throws the reference away, while the 5th line calls `.save()` on the class, which will fail. – David Eyk Mar 26 '13 at 19:04

1 Answers1

2

sender here is the Message class itself, not the instance that's being saved. The actual instance is passed as the keyword argument instance. Also, with post_save, if you're not careful, you'll get yourself in an infinite loop. Better to use pre_save.

@receiver(pre_save, sender=Message)
def my_handler(sender, **kwargs):
    instance = kwargs['instance']
    if not instance.charge:
        instance.charge = instance.length()
        # No need to save, as we're slipping the value in 
        # before we hit the database.
David Eyk
  • 12,171
  • 11
  • 63
  • 103