Django’s pre_save signal

2018-07-28

I found it useful for adding custom created_date and modified_date fields to a model without overriding its save method.

I’d find a method-based syntax nicer, but it’s OK.

This example helped me more than the documentation:

https://www.codingforentrepreneurs.com/blog/post-save-vs-pre-save-vs-override-save-method/

Here is how I used it:

from django.db import models
from django.db.models.signals import pre_save
from django.utils import timezone

class Learning(models.Model):
    [...]
    created_date = models.DateTimeField(blank=True)
    modified_date = models.DateTimeField(editable=False)
    [...]


# The fields created_date and modified_date are automatically created/modified but are still editable.
# Approach mostly based on:
# https://stackoverflow.com/questions/1737017/django-auto-now-and-auto-now-add#1737078
# But using pre_save signal instead of overriding the save method, like here:
# https://www.codingforentrepreneurs.com/blog/post-save-vs-pre-save-vs-override-save-method/

def add_dates(sender, instance, *args, **kwargs):
    # On save, update timestamps
    if not instance.id:
        instance.created_date = timezone.now()
    instance.modified_date = timezone.now()


pre_save.connect(add_dates, sender=Learning)