Complete the code to connect a signal to a receiver function in Django.
from django.db.models.signals import post_save from django.dispatch import receiver @receiver([1], sender=MyModel) def my_handler(sender, instance, **kwargs): print('Signal received')
The post_save signal is sent after a model's save() method completes. It is appropriate to connect to this signal to perform actions after saving an instance.
Complete the code to disconnect a signal receiver in Django.
from django.db.models.signals import post_save post_save.[1](my_handler, sender=MyModel)
The disconnect method removes a previously connected receiver from a signal.
Fix the error in the signal receiver to avoid side effects during testing.
@receiver(post_save, sender=MyModel) def my_handler(sender, instance, created, **kwargs): if [1]: send_welcome_email(instance.email)
Checking the created flag ensures the action runs only when a new instance is created, avoiding repeated side effects on updates.
Fill both blanks to create a signal receiver that avoids recursive saves.
@receiver(post_save, sender=MyModel) def update_related(sender, instance, [1], **[2]): if created: instance.related_model.update_status()
The receiver function should accept created to check if the instance is new, and kwargs to catch extra arguments. This helps avoid recursive saves by acting only on creation.
Fill all three blanks to write a signal receiver that updates a cache only when a model instance is deleted.
@receiver([1], sender=MyModel) def clear_cache(sender, instance, [2], **[3]): cache.delete(f'user_cache_{instance.pk}')
The pre_delete signal triggers before an instance is deleted. The receiver function should accept using and kwargs parameters to match the signal signature and avoid errors.