What is pre_save signal in Django and How to Use It
pre_save signal in Django is a hook that runs just before a model instance is saved to the database. It allows you to execute custom code or modify data right before saving happens.How It Works
The pre_save signal acts like a notification that Django sends out just before saving a model object to the database. Imagine you are about to mail a letter, and right before dropping it in the mailbox, you double-check the address or add a stamp. Similarly, pre_save lets you check or change the data before it is permanently stored.
When you connect a function (called a receiver) to this signal, Django calls that function every time before saving any instance of the model you specify. This gives you a chance to validate, modify, or log information before the save completes.
Example
This example shows how to use the pre_save signal to automatically set a model field before saving.
from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(blank=True) @receiver(pre_save, sender=Article) def set_slug(sender, instance, **kwargs): if not instance.slug: instance.slug = instance.title.lower().replace(' ', '-')
When to Use
Use pre_save when you need to adjust or check data right before saving it to the database. For example:
- Automatically generating or modifying fields like slugs or timestamps.
- Validating or cleaning data that depends on multiple fields.
- Logging or auditing changes before they are saved.
- Enforcing business rules that must run every time an object is saved.
This signal is helpful when you want to keep your model's save() method clean or when you want to separate concerns in your code.
Key Points
- pre_save runs just before a model instance is saved.
- You can modify the instance data before it hits the database.
- It helps keep save logic outside the model's
save()method. - Use it for automatic field updates, validation, or logging.
- Remember to connect your receiver function properly to the signal.