0
0
Djangoframework~20 mins

Receiver decorator in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Receiver Decorator in Django Signals
📖 Scenario: You are building a Django app where you want to perform an action automatically whenever a new user is created. Django signals help you do this by letting you run code when certain events happen.
🎯 Goal: Learn how to use the @receiver decorator to connect a function to Django's post_save signal for the User model. This function will print a welcome message whenever a new user is saved.
📋 What You'll Learn
Import the receiver decorator from django.dispatch
Import the post_save signal from django.db.models.signals
Import the User model from django.contrib.auth.models
Create a function that receives the post_save signal for User
Use the @receiver decorator to connect the function to the signal
💡 Why This Matters
🌍 Real World
Automatically running code when users register helps automate tasks like sending welcome messages or setting up profiles.
💼 Career
Understanding Django signals and the receiver decorator is important for backend developers working with Django to handle events cleanly and efficiently.
Progress0 / 4 steps
1
Set up imports and initial function
Write the import statements to bring in receiver from django.dispatch, post_save from django.db.models.signals, and User from django.contrib.auth.models. Then, define an empty function called welcome_new_user that takes sender, instance, created, and **kwargs as parameters.
Django
Need a hint?

Remember to import exactly receiver, post_save, and User. Define the function with the exact name and parameters.

2
Add the receiver decorator
Use the @receiver decorator to connect the welcome_new_user function to the post_save signal for the User model.
Django
Need a hint?

Use @receiver(post_save, sender=User) exactly above the function definition.

3
Add logic to check if user was created
Inside the welcome_new_user function, add an if statement that checks if created is True. This means the user was just created.
Django
Need a hint?

Use if created: to check if the user was newly created.

4
Print a welcome message for new users
Inside the if created: block, add a print statement that outputs "Welcome, " followed by the user's username from instance.username.
Django
Need a hint?

Use an f-string to include instance.username in the printed message.