Discover how a simple decorator can save you from tangled event code and bugs!
Why Receiver decorator in Django? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have to write code that listens for many different events in your Django app, like when a user logs in or a model is saved. You manually connect functions to these events everywhere in your code.
Manually connecting event handlers is easy to forget, can cause duplicate connections, and makes your code messy and hard to follow. It's like trying to remember to plug in every appliance separately instead of having a smart power strip.
The receiver decorator in Django lets you neatly attach your functions to signals in one place. It automatically connects your handler to the right event, keeping your code clean and reliable.
from django.db.models.signals import post_save post_save.connect(my_handler, sender=MyModel)
from django.dispatch import receiver from django.db.models.signals import post_save @receiver(post_save, sender=MyModel) def my_handler(sender, instance, **kwargs): pass
This lets you easily organize event-driven code, making your app responsive and maintainable without messy manual wiring.
When a new user signs up, you want to send a welcome email. Using the receiver decorator, you write a clean function that automatically runs after the user is saved, without extra setup.
Manually connecting signals is error-prone and cluttered.
The receiver decorator simplifies and organizes signal handling.
It helps keep your Django app clean and event-driven.
Practice
@receiver decorator in Django?Solution
Step 1: Understand what signals do in Django
Signals notify parts of your app when something happens, like saving a model.Step 2: Role of the
The decorator links a function to a signal so it runs automatically when the signal is sent.@receiverdecoratorFinal Answer:
To connect a function to a signal so it runs automatically when the signal is sent -> Option CQuick Check:
Receiver decorator connects functions to signals = D [OK]
- Confusing receiver with model or URL definitions
- Thinking receiver creates models or templates
- Mixing up signals with URL routing
@receiver decorator for the post_save signal of a model named Book?Solution
Step 1: Check the correct decorator syntax
The@receiverdecorator takes the signal as first argument andsender=ModelNameas keyword argument.Step 2: Match the correct function signature
The handler function must acceptsender,instance, and**kwargs.Final Answer:
@receiver(post_save, sender=Book) def my_handler(sender, instance, **kwargs): pass -> Option AQuick Check:
Correct decorator syntax = C [OK]
- Passing sender as positional argument
- Incorrect function parameters
- Missing sender keyword argument
Book instance is saved?
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Book)
def notify(sender, instance, **kwargs):
print(f"Book saved: {instance.title}")
book = Book(title='Django Basics')
book.save()Solution
Step 1: Understand the signal connection
The@receiverdecorator connectsnotifytopost_saveforBook.Step 2: What happens on
Saving the book triggersbook.save()?post_save, callingnotify, which prints the book's title.Final Answer:
Book saved: Django Basics -> Option DQuick Check:
post_save triggers print with instance title = B [OK]
- Assuming no output without explicit call
- Confusing instance attribute access
- Thinking receiver needs manual call
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Author)
def handle_save(instance, **kwargs):
print(f"Author saved: {instance.name}")Solution
Step 1: Check function parameters for signal handlers
Signal handlers must acceptsender,instance, and**kwargs.Step 2: Identify missing parameter
The functionhandle_savelacks thesenderparameter, causing an error.Final Answer:
Missingsenderparameter in function definition -> Option BQuick Check:
Signal handler must have sender parameter = A [OK]
- Omitting sender parameter
- Wrong function signature order
- Assuming function name matters
User model instance is created (not updated). How do you use the @receiver decorator with post_save to achieve this?Solution
Step 1: Understand the
Thecreatedflag inpost_savepost_savesignal passes acreatedboolean indicating if the instance was newly created.Step 2: Use
Checkcreatedto run code only on creationif created:inside the receiver function to run code only when a new instance is created.Final Answer:
@receiver(post_save, sender=User) def user_created(sender, instance, created, **kwargs): if created: print('New user created') -> Option AQuick Check:
Use created flag in post_save receiver = A [OK]
- Ignoring the created parameter
- Checking created incorrectly
- Missing created parameter in function
