Question

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!

Was it helpful?

Solution

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top