A.Lang A.Lang - 3 months ago 14
Bash Question

Signals working only in shell,not working in admin and frontend

I am trying to assign some values to a model field after post-save.The model is

class Authority(models.Model):
no_of_feeds=models.PositiveIntegerField()
no_of_rf=models.PositiveIntegerField()
no_of_urf=models.PositiveIntegerField()


class Feed(models.Model):
auth=models.ForeignKey(Authority,blank=False)

@receiver(post_save, sender = Feed)
def update_model_feed(sender, **kwargs):
if kwargs['created']: #only fire when creating new objects
kwargs['instance'].auth.no_of_feeds=kwargs['instance'].auth.feed_set.all().count()
kwargs['instance'].auth.no_of_rf=kwargs['instance'].auth.feed_set.filter(resolved=True).count()
kwargs['instance'].auth.no_of_urf=kwargs['instance'].auth.feed_set.filter(resolved=False).count()
print '******************************'
elif not kwargs['created']:
kwargs['instance'].auth.no_of_feeds=kwargs['instance'].auth.feed_set.all().count()
kwargs['instance'].auth.no_of_rf=kwargs['instance'].auth.feed_set.filter(resolved=True).count()
print '-------------------------------'
kwargs['instance'].auth.no_of_urf=kwargs['instance'].auth.feed_set.filter(resolved=False).count()


As you can see,The signal is used to assign values to
Authority
fields after saving
Feed
model.This works in shell,as the fields are automatically updated but it doesnt work on creating or editing a feed instance in admin or front-end website.Though its print out the '-------' and '****' on execution in the console.Pls kindly help

Answer

Need to do kwargs['instance'].auth.save() in order to write those changes to the related Authority to the database. If I had to guess, it looks like it's working in the shell because you're looking at the unsaved object in memory, while on your working site you're looking at the values returned from the database.

Comments