0
0
Djangoframework~10 mins

Connecting signal handlers in Django - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the Django signal dispatcher.

Django
from django.dispatch import [1]
Drag options to blanks, or click blank then click option'
ASignal
Breceiver
Cconnect
Dsend
Attempts:
3 left
💡 Hint
Common Mistakes
Importing 'Signal' instead of 'receiver'.
Trying to import 'connect' which is a method, not an import.
Using 'send' which is a method to send signals, not to connect handlers.
2fill in blank
medium

Complete the code to connect a signal handler to the post_save signal of a model.

Django
@receiver([1], sender=MyModel)
def my_handler(sender, instance, **kwargs):
    pass
Drag options to blanks, or click blank then click option'
Apre_delete
Bpre_save
Cpost_save
Dpost_delete
Attempts:
3 left
💡 Hint
Common Mistakes
Using pre_save which triggers before saving.
Using delete signals instead of save signals.
Not specifying the correct signal name.
3fill in blank
hard

Fix the error in the signal handler connection by completing the missing import.

Django
from django.db.models.signals import [1]

@receiver(post_save, sender=User)
def user_saved(sender, instance, **kwargs):
    print('User saved!')
Drag options to blanks, or click blank then click option'
Apre_save
Bpost_delete
Cpre_delete
Dpost_save
Attempts:
3 left
💡 Hint
Common Mistakes
Importing the wrong signal.
Not importing the signal at all.
Importing signals from the wrong module.
4fill in blank
hard

Fill both blanks to connect a handler to the pre_delete signal for the Article model.

Django
from django.db.models.signals import [1]

@receiver([2], sender=Article)
def before_delete(sender, instance, **kwargs):
    print('Article will be deleted')
Drag options to blanks, or click blank then click option'
Apre_delete
Bpost_save
Cpre_save
Dpost_delete
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing different signals in import and decorator.
Using save signals instead of delete signals.
Forgetting to import the signal.
5fill in blank
hard

Fill all three blanks to create a signal handler that listens to post_save for Profile and prints the instance's username.

Django
from django.db.models.signals import [1]
from django.dispatch import [2]

@[2]([1], sender=Profile)
def profile_saved(sender, instance, **kwargs):
    print(f"Saved profile for {instance.username}")
Drag options to blanks, or click blank then click option'
Apost_save
Breceiver
Cpre_save
Dpost_delete
Attempts:
3 left
💡 Hint
Common Mistakes
Using different decorators in import and usage.
Importing the wrong signal.
Not matching the signal in import and decorator.