0
0
Djangoframework~3 mins

Why pre_save and post_save signals in Django? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to automate tasks around saving data without cluttering your code!

The Scenario

Imagine you have a website where users can upload profiles. Every time a profile is saved, you want to send a welcome email and update some statistics manually by adding code everywhere you save the profile.

The Problem

Manually adding code to send emails or update stats in every save location is easy to forget, leads to duplicated code, and makes your app hard to maintain and debug.

The Solution

Django's pre_save and post_save signals let you run code automatically before or after any model is saved, keeping your logic clean and centralized.

Before vs After
Before
def save_profile(profile):
    profile.save()
    send_welcome_email(profile)
    update_stats(profile)
After
from django.db.models.signals import post_save

from django.dispatch import receiver

@receiver(post_save, sender=Profile)
def send_email(sender, instance, created, **kwargs):
    if created:
        send_welcome_email(instance)
What It Enables

You can add extra actions tied to saving data without changing your main save code, making your app easier to grow and maintain.

Real Life Example

When a new blog post is saved, automatically update the author's post count and notify followers without touching the blog post save logic.

Key Takeaways

Manually handling save-related tasks causes repeated and fragile code.

pre_save and post_save signals run code automatically around saving.

This keeps your app organized and easier to update.