Bird
0
0

Given this code snippet, what will be printed when a new User instance is saved?

medium📝 component behavior Q13 of 15
Django - Signals
Given this code snippet, what will be printed when a new User instance is saved?
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def user_saved(sender, instance, created, **kwargs):
    if created:
        print(f"User {instance.username} created")
    else:
        print(f"User {instance.username} updated")

user = User(username='alice')
user.save()
AUser alice updated
BUser alice created
CNo output
DError: receiver not connected
Step-by-Step Solution
Solution:
  1. Step 1: Understand the post_save signal and receiver

    The receiver listens for post_save on User. It prints 'created' if the instance is new.
  2. Step 2: Analyze the save call

    Creating a new User and calling save triggers post_save with created=True, so it prints 'User alice created'.
  3. Final Answer:

    User alice created -> Option B
  4. Quick Check:

    New save triggers created=True message [OK]
Quick Trick: post_save with created=True means new instance saved [OK]
Common Mistakes:
MISTAKES
  • Assuming updated message prints on new save
  • Thinking receiver is not connected automatically
  • Ignoring the created flag in the receiver

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes