0
0
Djangoframework~5 mins

Connecting signal handlers in Django - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a signal handler in Django?
A signal handler is a function that gets called automatically when a specific event (signal) happens in Django, like saving a model or user login.
Click to reveal answer
beginner
How do you connect a signal handler to a signal in Django?
You use the connect() method on the signal, passing the handler function and optionally the sender model to listen for specific events.
Click to reveal answer
intermediate
Why should you connect signal handlers inside the apps.py or a ready method?
Connecting signals in apps.py ensures handlers are registered only once when the app starts, avoiding duplicate calls or missed signals.
Click to reveal answer
intermediate
What does the sender argument do when connecting a signal handler?
The sender argument limits the signal handler to respond only to signals sent by that specific model or class.
Click to reveal answer
beginner
Show a simple example of connecting a signal handler to Django's post_save signal.
from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import MyModel

@receiver(post_save, sender=MyModel)
def my_handler(sender, instance, created, **kwargs):
    if created:
        print(f"New instance created: {instance}")
Click to reveal answer
What method do you use to connect a signal handler in Django?
Aregister()
Bbind()
Cconnect()
Dattach()
Where is the best place to connect signal handlers to avoid multiple registrations?
AInside apps.py in the ready() method
BInside models.py
CInside views.py
DInside templates
What does the sender argument specify when connecting a signal?
AThe function to call
BThe model or class sending the signal
CThe signal type
DThe database connection
Which Django signal is commonly used to run code after a model instance is saved?
Apost_save
Bpre_save
Cpre_delete
Dpost_delete
What happens if you connect the same signal handler multiple times?
AIt runs only once
BIt disables the signal
CIt causes an error
DIt runs multiple times for one event
Explain how to connect a signal handler in Django and why it is important to do it in the right place.
Think about app startup and avoiding duplicate calls.
You got /4 concepts.
    Describe the role of the sender argument when connecting a signal handler in Django.
    Sender is like choosing which friend’s message you want to listen to.
    You got /3 concepts.