0
0
Djangoframework~30 mins

pre_delete and post_delete signals in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Using pre_delete and post_delete Signals in Django
📖 Scenario: You are building a simple Django app to manage a list of books. You want to perform actions right before and right after a book is deleted from the database.
🎯 Goal: Create a Django model for books and use pre_delete and post_delete signals to print messages when a book is about to be deleted and after it has been deleted.
📋 What You'll Learn
Create a Django model called Book with a title field
Import and connect pre_delete and post_delete signals
Write signal handler functions named before_book_delete and after_book_delete
Connect the signal handlers to the Book model
Use print() statements inside handlers to show messages
💡 Why This Matters
🌍 Real World
In real apps, signals help run code automatically when database changes happen, like cleaning up related data or logging actions.
💼 Career
Understanding Django signals is important for backend developers to manage side effects and keep data consistent in web applications.
Progress0 / 4 steps
1
Create the Book model
Create a Django model called Book with a single field title that is a CharField with max length 100.
Django
Need a hint?

Use models.CharField(max_length=100) for the title field inside the Book class.

2
Import signals and define handler functions
Import pre_delete and post_delete from django.db.models.signals. Define two functions: before_book_delete and after_book_delete that take sender, instance, and **kwargs as parameters. Inside each function, add a print() statement with messages "About to delete: " plus the book title, and "Deleted: " plus the book title, respectively.
Django
Need a hint?

Remember to use f-strings to include the book title in the print messages.

3
Connect the signal handlers to the Book model
Use the connect() method on pre_delete and post_delete to connect before_book_delete and after_book_delete functions to the Book model.
Django
Need a hint?

Use pre_delete.connect(your_function, sender=Book) to connect the signal.

4
Complete the Django app setup
Add the necessary import for apps.py to ensure signals are registered when the app is ready. Import the signals module inside the ready() method of your app config class named BooksConfig.
Django
Need a hint?

Import the signals module inside the ready() method to register signal handlers.