Django 4.0 - implementing Signal Handling for Model Save Events Causing Infinite Loop
I'm updating my dependencies and I'm not sure how to approach I'm stuck on something that should probably be simple..... I'm relatively new to this, so bear with me. I'm running into a question with Django 4.0 where I'm trying to use signals to perform some actions after saving a model instance. However, it's causing an infinite loop and crashing my server. I have a model `Book` and a signal receiver set up to create an entry in another model `Log` every time a `Book` instance is saved. Here's what I've implemented: ```python from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=100) class Log(models.Model): message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) @receiver(post_save, sender=Book) def create_log(sender, instance, created, **kwargs): if created: Log.objects.create(message=f'New book added: {instance.title}') # This line seems to trigger an infinite loop instance.title = instance.title + ' - New' instance.save() # Causes infinite loop ``` When I save a new `Book` instance, the signal works as expected and creates a log entry, but then it goes back to save the `Book` again because I modified its title. This leads to the signal firing repeatedly until the server crashes due to too many requests. I tried adding a condition to prevent the modification if the instance already exists, but it seems not to help. I also considered using `update_fields` in the `save()` call, but I still end up in the same loop. How can I modify the instance without triggering the signal handling again? Is there a design pattern or approach that I should use to avoid this infinite loop? Thanks in advance! I'd really appreciate any guidance on this. Is this even possible? This is my first time working with Python 3.10. What's the best practice here?