[Fixed]-Django Signals, how to know when an update happen?

1👍

@receiver(post_save, sender=Post, dispatch_uid="update_stock_count")
def criar_slug(sender, instance, created,**kwargs):
    if kwargs['created'] or 'city' in kwargs['update_fields'] or 'title' in kwargs['update_fields'] :
        string = (instance.city+" "+instance.title+" "+str(instance.id))
        instance.slug = slugify(string)
        instance.save()

0👍

You want to remove if created flag so that you can change the slug field.

Refer following solution

Use init signal to store previous value of filed so that you can check that field modified or not in post signal.

@receiver(post_init, sender=Post)
def lead_post_init(sender, instance, **kwargs):
    instance._previous_city = instance.city
    instance._previous_title = instance.title

@receiver(post_save, sender=Post, dispatch_uid="update_stock_count")
def criar_slug(sender, instance, created,**kwargs):
    if instance._previous_city != instance.city or instance._previous_title != instance.title:
        string = (instance.city+" "+instance.title+" "+str(instance.id))
        instance.slug = slugify(string)
        instance.save()

Hope this is helps you

Leave a comment