Bird
Raised Fist0
Djangoframework~20 mins

Connecting signal handlers in Django - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Signal Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a signal handler is connected incorrectly?
Consider this Django signal connection code:
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=MyModel)
def my_handler(sender, instance, **kwargs):
    print('Saved:', instance)

What will happen if you forget to import MyModel correctly and connect the signal?
AThe signal handler will be called for all models, ignoring the sender filter.
BDjango will raise an ImportError at runtime when connecting the signal.
CThe signal handler will be called twice for each save event.
DThe signal handler will never be called because the sender is not recognized.
Attempts:
2 left
💡 Hint
Think about how the sender argument filters which model triggers the signal.
📝 Syntax
intermediate
1:30remaining
Which option correctly connects a signal handler using the connect method?
You want to connect a function my_handler to Django's post_delete signal for MyModel. Which code snippet is correct?
Apost_delete.connect(my_handler, sender=MyModel)
Bpost_delete.connect(sender=MyModel, my_handler)
Cpost_delete.connect(my_handler)
Dpost_delete.connect(my_handler, MyModel)
Attempts:
2 left
💡 Hint
Remember the order of arguments for the connect method.
state_output
advanced
2:00remaining
What is printed when a signal handler modifies instance data before saving?
Given this code:
from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=MyModel)
def modify_name(sender, instance, **kwargs):
    instance.name = instance.name.upper()

obj = MyModel(name='hello')
obj.save()
print(obj.name)

What will be printed?
Ahello
BHELLO
CNone
DAn error is raised
Attempts:
2 left
💡 Hint
The pre_save signal runs before the model instance is saved.
🔧 Debug
advanced
2:30remaining
Why does this signal handler run multiple times unexpectedly?
This code connects a signal handler inside a Django view function:
def my_view(request):
    from django.db.models.signals import post_save

    def handler(sender, instance, **kwargs):
        print('Saved:', instance)

    post_save.connect(handler, sender=MyModel)
    # ... rest of view code ...
    return HttpResponse('Done')

Why might the handler print multiple times on multiple requests?
ABecause the signal connection happens on every request, adding duplicate handlers.
BBecause post_save signals are only sent once per model class.
CBecause the handler function is defined inside the view, it is not recognized.
DBecause Django caches signal handlers and reuses them.
Attempts:
2 left
💡 Hint
Think about where the connect call is placed and how often the view runs.
🧠 Conceptual
expert
3:00remaining
What is the effect of using dispatch_uid when connecting signal handlers?
In Django signals, what does providing a unique dispatch_uid argument to connect do?
AFilters signals to only those with matching dispatch_uid.
BChanges the order in which signal handlers are called.
CPrevents the same signal handler from being connected multiple times.
DMakes the signal handler run asynchronously.
Attempts:
2 left
💡 Hint
Think about how Django avoids duplicate signal connections.

Practice

(1/5)
1. What is the main purpose of connecting signal handlers in Django?
easy
A. To style HTML templates dynamically
B. To manually call functions from views
C. To create new database tables
D. To automatically run code when certain model events happen

Solution

  1. Step 1: Understand signal handlers

    Signal handlers let Django apps respond automatically to events like saving or deleting a model.
  2. Step 2: Identify the purpose

    Connecting signal handlers means running code automatically when these events happen, without manual calls.
  3. Final Answer:

    To automatically run code when certain model events happen -> Option D
  4. Quick Check:

    Signal handlers = automatic event response [OK]
Hint: Signals run code automatically on model events [OK]
Common Mistakes:
  • Thinking signals create database tables
  • Confusing signals with manual function calls
  • Assuming signals style templates
2. Which of the following is the correct way to connect a signal handler using the decorator in Django?
easy
A. @receiver(post_save, sender=MyModel) def my_handler(sender, instance, **kwargs): pass
B. @signal(post_save, sender=MyModel) def my_handler(sender, instance): pass
C. @connect(post_save, sender=MyModel) def my_handler(instance): pass
D. @listen(post_save, sender=MyModel) def my_handler(sender): pass

Solution

  1. Step 1: Recall the correct decorator

    Django uses @receiver to connect signal handlers, not @signal, @connect, or @listen.
  2. Step 2: Check function parameters

    The handler must accept sender, instance, and optionally **kwargs. @receiver(post_save, sender=MyModel) def my_handler(sender, instance, **kwargs): pass matches this.
  3. Final Answer:

    @receiver(post_save, sender=MyModel) def my_handler(sender, instance, **kwargs): pass -> Option A
  4. Quick Check:

    Use @receiver with correct params [OK]
Hint: Use @receiver decorator with sender and signal [OK]
Common Mistakes:
  • Using wrong decorator names
  • Missing sender argument
  • Incorrect handler parameters
3. Given this code snippet, what will be printed when a new Book instance is created?
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Book)
def announce_book(sender, instance, created, **kwargs):
    if created:
        print(f"New book added: {instance.title}")

book = Book.objects.create(title='Django Basics')
medium
A. New book added:
B. New book added: Django Basics
C. No output
D. Error: missing argument

Solution

  1. Step 1: Understand the signal and handler

    The post_save signal triggers after saving a model. The handler checks if created is True, meaning a new record.
  2. Step 2: Analyze the code execution

    Creating a new Book instance sets created=True, so the print statement runs with the title.
  3. Final Answer:

    New book added: Django Basics -> Option B
  4. Quick Check:

    post_save with created=True prints title [OK]
Hint: Check 'created' flag to print on new records only [OK]
Common Mistakes:
  • Ignoring the 'created' flag
  • Assuming no output on create
  • Confusing signal arguments
4. Identify the error in this signal handler connection code:
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save)
def handler(sender, instance, **kwargs):
    print('Saved!')
medium
A. Missing sender argument in @receiver decorator
B. Handler function missing 'created' parameter
C. post_save signal is not imported correctly
D. Handler function should not have **kwargs

Solution

  1. Step 1: Check the @receiver decorator usage

    The @receiver decorator requires the signal and optionally the sender. Omitting sender means the handler listens to all senders, which is allowed but often unintended.
  2. Step 2: Identify the likely error

    Since the question asks for an error, the missing sender argument is the problem if the handler is meant for a specific model.
  3. Final Answer:

    Missing sender argument in @receiver decorator -> Option A
  4. Quick Check:

    Specify sender to target model signals [OK]
Hint: Always specify sender to avoid catching all signals [OK]
Common Mistakes:
  • Not specifying sender when needed
  • Assuming 'created' param is always required
  • Misunderstanding **kwargs usage
5. You want to run a function only when a new UserProfile is created, not when updated. Which is the best way to connect the signal handler?
hard
A. Use @receiver(post_save) without sender and ignore created flag
B. Use @receiver(pre_save, sender=UserProfile) and always run the function
C. Use @receiver(post_save, sender=UserProfile) and check if created is True inside the handler
D. Use @receiver(post_delete, sender=UserProfile) to detect creation

Solution

  1. Step 1: Identify the correct signal for creation

    post_save runs after saving, and the created flag tells if it's a new record.
  2. Step 2: Choose the best method

    Using @receiver(post_save, sender=UserProfile) and checking created inside the handler ensures the function runs only on creation.
  3. Final Answer:

    Use @receiver(post_save, sender=UserProfile) and check if created is True inside the handler -> Option C
  4. Quick Check:

    post_save + created=True = run on new only [OK]
Hint: Check 'created' flag in post_save for new records only [OK]
Common Mistakes:
  • Using pre_save which runs before saving
  • Using post_delete which runs on deletion
  • Ignoring the created flag and running always