Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The Django post_save() signal can be implemented by following these steps:

  1. Import the signals module from Django:
from django.db.models.signals import post_save
  1. Import the model you want to create the signal for:
from myapp.models import MyModel
  1. Define a function that will handle the post-save signal:
def my_signal_receiver(sender, instance, created, **kwargs):
    if created:
        print("A new object has been created:", instance)
    else:
        print("An object has been updated:", instance)

In this example, the function takes four arguments:

  • sender: The class of the model that sent the signal (in this case, MyModel).
  • instance: The instance of the model that was saved.
  • created: A boolean that indicates whether the instance was created or updated.
  1. Connect the function to the post_save signal for the MyModel model:
post_save.connect(my_signal_receiver, sender=MyModel)

This connects the function mysignalreceiver to the post_save signal for the MyModel model. Whenever a MyModel instance is saved or updated, the function will be called.

Note: You can connect multiple functions to the post_save signal for the same model.