0
0
Djangoframework~20 mins

Connecting signal handlers in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Connecting signal handlers in Django
📖 Scenario: You are building a Django app that needs to perform an action automatically whenever a new user is created. Django signals let you run code in response to certain events, like saving a model.
🎯 Goal: Learn how to connect a signal handler function to Django's post_save signal for the User model. This handler will print a message when a new user is created.
📋 What You'll Learn
Create a signal handler function named welcome_new_user that accepts sender, instance, created, and **kwargs parameters.
Connect the welcome_new_user function to Django's post_save signal for the User model.
Ensure the handler only runs when a new user is created (not updated).
Import all necessary modules and models correctly.
💡 Why This Matters
🌍 Real World
Automatically running code when users sign up helps send welcome messages, set up profiles, or log activity without manual steps.
💼 Career
Understanding Django signals is important for backend developers to create clean, event-driven code that reacts to database changes.
Progress0 / 4 steps
1
Import User model and post_save signal
Write import statements to import User from django.contrib.auth.models and post_save from django.db.models.signals.
Django
Need a hint?

Use from django.contrib.auth.models import User and from django.db.models.signals import post_save.

2
Define the signal handler function
Define a function named welcome_new_user that takes parameters sender, instance, created, and **kwargs. Inside the function, add an if statement to check if created is True. If so, write a comment inside the block saying # New user created.
Django
Need a hint?

Define the function with the exact name and parameters. Use if created: to check if the user is new.

3
Connect the signal handler to post_save for User
Use post_save.connect to connect the welcome_new_user function to the post_save signal for the User model. Pass sender=User as an argument.
Django
Need a hint?

Use post_save.connect(welcome_new_user, sender=User) to connect the handler.

4
Add a print statement inside the handler
Inside the if created: block of welcome_new_user, add a print statement that outputs Welcome, {instance.username}! using an f-string.
Django
Need a hint?

Use print(f"Welcome, {instance.username}!") inside the if created: block.