0
0
Djangoframework~5 mins

pre_save and post_save signals in Django

Choose your learning style9 modes available
Introduction

These signals let you run code automatically before or after saving data in the database. It helps keep your app organized and react to changes easily.

You want to check or change data before saving it to the database.
You need to update related data right after saving a record.
You want to send notifications or logs when data changes.
You want to enforce rules or validations automatically on save.
Syntax
Django
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from your_app.models import YourModel

@receiver(pre_save, sender=YourModel)
def before_save(sender, instance, **kwargs):
    # code to run before saving
    pass

@receiver(post_save, sender=YourModel)
def after_save(sender, instance, created, **kwargs):
    # code to run after saving
    # 'created' is True if new record was created
    pass

Use @receiver decorator to connect your function to the signal.

The instance is the actual model object being saved.

Examples
This sets a default title if none is given before saving a Book.
Django
from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import Book

@receiver(pre_save, sender=Book)
def set_default_title(sender, instance, **kwargs):
    if not instance.title:
        instance.title = 'Untitled Book'
This prints a message after a new Book is saved.
Django
from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import Book

@receiver(post_save, sender=Book)
def notify_new_book(sender, instance, created, **kwargs):
    if created:
        print(f'New book added: {instance.title}')
Sample Program

This example shows an Article model. Before saving, it sets a default title if none is given. After saving, it prints if the article was created or updated.

Django
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver

class Article(models.Model):
    title = models.CharField(max_length=100, blank=True)
    content = models.TextField()

@receiver(pre_save, sender=Article)
def ensure_title(sender, instance, **kwargs):
    if not instance.title:
        instance.title = 'Default Title'

@receiver(post_save, sender=Article)
def announce_article(sender, instance, created, **kwargs):
    if created:
        print(f'Article created: {instance.title}')
    else:
        print(f'Article updated: {instance.title}')
OutputSuccess
Important Notes

Signals run automatically without changing your save() calls.

Be careful to avoid infinite loops if you save inside a signal handler.

Use signals to keep code clean and separate concerns.

Summary

pre_save runs before saving data to check or modify it.

post_save runs after saving to react to changes.

Use signals to automate tasks and keep your app organized.