Discover how to automate tasks around saving data without cluttering your code!
Why pre_save and post_save signals in Django? - Purpose & Use Cases
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.
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.
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.
def save_profile(profile):
profile.save()
send_welcome_email(profile)
update_stats(profile)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)
You can add extra actions tied to saving data without changing your main save code, making your app easier to grow and maintain.
When a new blog post is saved, automatically update the author's post count and notify followers without touching the blog post save logic.
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.