Bird
Raised Fist0
Djangoframework~30 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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
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
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
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
Hint

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

Practice

(1/5)
1. What is the main difference between Django's pre_delete and post_delete signals?
easy
A. pre_delete runs after a record is deleted, post_delete runs before.
B. pre_delete runs before a record is deleted, post_delete runs after.
C. Both signals run at the same time during deletion.
D. pre_delete only works with models, post_delete only with forms.

Solution

  1. Step 1: Understand signal timing

    pre_delete is triggered just before a model instance is deleted from the database.
  2. Step 2: Understand post_delete timing

    post_delete is triggered immediately after the instance has been deleted.
  3. Final Answer:

    pre_delete runs before a record is deleted, post_delete runs after. -> Option B
  4. Quick Check:

    Signal timing difference = pre_delete runs before a record is deleted, post_delete runs after. [OK]
Hint: Remember: pre_delete before removal, post_delete after removal [OK]
Common Mistakes:
  • Confusing the order of signal execution
  • Thinking both signals run simultaneously
  • Assuming signals work only with forms
2. Which of the following is the correct way to connect a pre_delete signal to a model named Book?
easy
A. Book.pre_delete.connect(my_handler)
B. post_delete.connect(my_handler, sender=Book)
C. pre_delete.connect(my_handler, sender=Book)
D. connect(pre_delete, my_handler, Book)

Solution

  1. Step 1: Recall signal connection syntax

    In Django, signals are connected using signal.connect(handler, sender=Model).
  2. Step 2: Apply to pre_delete and Book

    Use pre_delete.connect(my_handler, sender=Book) to connect the handler to the Book model.
  3. Final Answer:

    pre_delete.connect(my_handler, sender=Book) -> Option C
  4. Quick Check:

    Correct connect syntax = pre_delete.connect(my_handler, sender=Book) [OK]
Hint: Use signal.connect(handler, sender=Model) to connect signals [OK]
Common Mistakes:
  • Using post_delete instead of pre_delete
  • Trying to call connect on the model itself
  • Incorrect argument order in connect
3. Given this code snippet, what will be printed when a Book instance is deleted?
from django.db.models.signals import pre_delete, post_delete
from django.dispatch import receiver

@receiver(pre_delete, sender=Book)
def before_delete(sender, instance, **kwargs):
    print(f"Deleting book: {instance.title} (pre_delete)")

@receiver(post_delete, sender=Book)
def after_delete(sender, instance, **kwargs):
    print(f"Deleted book: {instance.title} (post_delete)")

book = Book(title='Django Basics')
book.delete()
medium
A. Deleting book: Django Basics (pre_delete) Deleted book: Django Basics (post_delete)
B. Deleted book: Django Basics (post_delete) Deleting book: Django Basics (pre_delete)
C. Only Deleting book: Django Basics (pre_delete) is printed
D. No output is printed

Solution

  1. Step 1: Understand signal order on deletion

    pre_delete runs before the instance is deleted, so its print runs first.
  2. Step 2: Understand post_delete runs after deletion

    After deletion, post_delete signal triggers, printing the second message.
  3. Final Answer:

    Deleting book: Django Basics (pre_delete) Deleted book: Django Basics (post_delete) -> Option A
  4. Quick Check:

    Signal print order = Deleting book: Django Basics (pre_delete) Deleted book: Django Basics (post_delete) [OK]
Hint: pre_delete prints before delete, post_delete prints after [OK]
Common Mistakes:
  • Assuming post_delete prints before pre_delete
  • Expecting only one signal to run
  • Forgetting to call delete() on the instance
4. What is wrong with this code that tries to use pre_delete signal?
from django.db.models.signals import pre_delete

@pre_delete(sender=Author)
def cleanup(sender, instance, **kwargs):
    print('Cleaning up author data')
medium
A. Using @pre_delete decorator is incorrect; should use @receiver instead.
B. Missing import for Author model.
C. Signal handler must return a value.
D. The function name 'cleanup' is reserved and cannot be used.

Solution

  1. Step 1: Check signal handler decoration

    Django signals use the @receiver(signal, sender=Model) decorator, not @pre_delete(sender=Model).
  2. Step 2: Confirm correct decorator usage

    Replace @pre_delete(sender=Author) with @receiver(pre_delete, sender=Author) to fix the error.
  3. Final Answer:

    Using @pre_delete decorator is incorrect; should use @receiver instead. -> Option A
  4. Quick Check:

    Use @receiver for signals, not @pre_delete [OK]
Hint: Use @receiver(signal, sender=Model) to decorate signal handlers [OK]
Common Mistakes:
  • Using signal name as decorator directly
  • Forgetting to import @receiver
  • Assuming signal handlers must return values
5. You want to automatically delete all Comment objects related to a Post before the Post itself is deleted. Which signal and approach is best?
hard
A. Use post_delete on Comment to delete the post after comments are removed.
B. Use post_delete on Post to delete related Comment objects after the post is removed.
C. Use pre_delete on Comment to delete the post before comments are removed.
D. Use pre_delete on Post to delete related Comment objects before the post is removed.

Solution

  1. Step 1: Understand deletion order requirement

    Comments must be deleted before the post to avoid foreign key errors.
  2. Step 2: Choose correct signal and model

    pre_delete on Post allows deleting related comments before the post is removed.
  3. Final Answer:

    Use pre_delete on Post to delete related Comment objects before the post is removed. -> Option D
  4. Quick Check:

    Delete related objects in pre_delete to avoid FK errors [OK]
Hint: Delete related objects in pre_delete to prevent FK constraint errors [OK]
Common Mistakes:
  • Deleting related objects after post deletion causes errors
  • Using signals on wrong model
  • Trying to delete parent in comment signals