Bird
0
0

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

medium📝 component behavior Q4 of 15
Django - Signals
Given this code snippet, what will happen 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 welcome_email(sender, instance, created, **kwargs):
    if created:
        print(f"Welcome email sent to {instance.email}")
APrints the message every time any user is saved, new or existing
BRaises an error because the signal is not connected properly
CPrints 'Welcome email sent to' with the user's email only when a new user is created
DDoes nothing because the function is not called explicitly
Step-by-Step Solution
Solution:
  1. Step 1: Understand the @receiver decorator usage

    The decorator connects the welcome_email function to the post_save signal for the User model.
  2. Step 2: Analyze the function behavior on save

    The function checks if the instance is newly created (created == True) and prints the welcome message only then.
  3. Final Answer:

    Prints 'Welcome email sent to' with the user's email only when a new user is created -> Option C
  4. Quick Check:

    post_save with created=True triggers welcome message [OK]
Quick Trick: @receiver decorates to auto-connect signals [OK]
Common Mistakes:
MISTAKES
  • Thinking message prints on every save
  • Assuming explicit connect call is needed
  • Believing function won't run without manual call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes