0
0
Djangoframework~30 mins

Custom signals in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Custom Signals in Django
📖 Scenario: You are building a Django app that needs to perform an action whenever a new user profile is created. Instead of putting this logic directly in the view or model, you will use a custom signal to keep your code clean and organized.
🎯 Goal: Create a custom Django signal called profile_created that triggers when a new user profile is saved. Connect a receiver function to this signal that prints a message confirming the profile creation.
📋 What You'll Learn
Create a custom signal named profile_created
Define a receiver function called profile_created_receiver
Connect the receiver to the profile_created signal
Send the profile_created signal after saving a new profile
💡 Why This Matters
🌍 Real World
Custom signals help keep Django apps organized by separating event handling logic from models and views. This is useful in large projects where multiple actions need to happen after certain events.
💼 Career
Understanding custom signals is important for Django developers to write clean, maintainable code and to implement event-driven features in web applications.
Progress0 / 4 steps
1
Create the custom signal
In a file called signals.py, import Signal from django.dispatch and create a custom signal named profile_created.
Django
Need a hint?

Use Signal() to create a new signal object.

2
Define the receiver function
In signals.py, define a function called profile_created_receiver that accepts sender and **kwargs parameters. Inside the function, write a comment saying # This function will handle the signal.
Django
Need a hint?

The receiver function must accept sender and **kwargs.

3
Connect the receiver to the signal
Still in signals.py, connect the profile_created_receiver function to the profile_created signal using the connect method.
Django
Need a hint?

Use profile_created.connect(profile_created_receiver) to link the receiver.

4
Send the signal after saving a profile
In your models.py, after saving a new profile instance, import profile_created from signals and send the signal using profile_created.send(sender=Profile, instance=profile) where profile is the saved instance.
Django
Need a hint?

Override the save method in the Profile model to send the signal after saving.