0
0
Djangoframework~30 mins

pre_save and post_save signals in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Django pre_save and post_save Signals
📖 Scenario: You are building a simple Django app to manage books in a library. You want to automatically update a timestamp before saving a book and log a message after saving it.
🎯 Goal: Create a Django model for Book and use pre_save and post_save signals to update a field and print a message.
📋 What You'll Learn
Create a Book model with fields title (string) and last_updated (DateTimeField).
Create a pre_save signal handler that updates last_updated to the current time before saving.
Create a post_save signal handler that prints 'Book saved!' after saving.
Connect the signal handlers properly to the Book model.
💡 Why This Matters
🌍 Real World
Automatically updating timestamps and triggering actions on model changes is common in web apps for data integrity and notifications.
💼 Career
Understanding Django signals is important for backend developers to handle side effects and keep code clean and modular.
Progress0 / 4 steps
1
Create the Book model
Create a Django model called Book with a title field as models.CharField(max_length=100) and a last_updated field as models.DateTimeField(null=True, blank=True).
Django
Need a hint?

Use models.CharField for the title and models.DateTimeField for last_updated with null=True and blank=True.

2
Create a pre_save signal handler
Import pre_save from django.db.models.signals and receiver from django.dispatch. Create a function called update_last_updated that takes sender, instance, and **kwargs. Inside it, set instance.last_updated to timezone.now(). Use @receiver(pre_save, sender=Book) to connect it.
Django
Need a hint?

Use @receiver(pre_save, sender=Book) decorator and set instance.last_updated = timezone.now().

3
Create a post_save signal handler
Import post_save from django.db.models.signals. Create a function called notify_book_saved that takes sender, instance, created, and **kwargs. Inside it, print the string 'Book saved!'. Use @receiver(post_save, sender=Book) to connect it.
Django
Need a hint?

Use @receiver(post_save, sender=Book) and print 'Book saved!' inside the function.

4
Connect signals in apps.py
In your app's apps.py, import AppConfig from django.apps. Create a class called LibraryConfig inheriting from AppConfig with name = 'library'. Override the ready() method to import the models module with import library.models.
Django
Need a hint?

Override ready() in LibraryConfig to import library.models so signals connect on app start.