0
0
DjangoConceptBeginner · 3 min read

What is post_save signal in Django: Explanation and Example

In Django, the post_save signal is triggered automatically right after a model's save() method completes. It allows you to run custom code whenever a model instance is created or updated.
⚙️

How It Works

The post_save signal in Django acts like a notification system that tells your app when a model object has just been saved to the database. Imagine you have a friend who calls you every time they finish a task; similarly, Django 'calls' your signal handler after saving.

This signal sends information about the saved object, whether it was newly created or just updated, and other details. You can connect your own function to this signal to perform extra actions, like sending an email, updating related data, or logging changes.

💻

Example

This example shows how to use the post_save signal to print a message whenever a Book model is saved.

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=100)
    author = models.CharField(max_length=100)

@receiver(post_save, sender=Book)
def book_saved(sender, instance, created, **kwargs):
    if created:
        print(f"A new book titled '{instance.title}' was added.")
    else:
        print(f"The book titled '{instance.title}' was updated.")
Output
A new book titled 'Django Basics' was added.
🎯

When to Use

Use the post_save signal when you want to automatically trigger actions right after saving a model. For example:

  • Send a welcome email when a new user registers.
  • Update a summary or cache after data changes.
  • Log changes for audit purposes.
  • Create related objects automatically after saving.

This helps keep your code organized by separating side effects from the main save logic.

Key Points

  • post_save runs after a model instance is saved.
  • You can detect if the instance was created or updated.
  • It helps automate tasks triggered by data changes.
  • Use @receiver decorator to connect functions cleanly.

Key Takeaways

The post_save signal runs automatically after saving a Django model instance.
It allows running custom code when an object is created or updated.
Use it to automate tasks like sending emails, logging, or updating related data.
Connect your handler functions with the @receiver decorator for clarity.
Signals help keep your code modular by separating side effects from main logic.