0
0
Djangoframework~30 mins

When signals are appropriate vs not in Django - Hands-On Comparison

Choose your learning style9 modes available
Understanding When to Use Django Signals
📖 Scenario: You are building a Django web application that manages user profiles and sends notifications when profiles are updated.You want to learn when to use Django signals to handle automatic actions and when to avoid them for clearer code.
🎯 Goal: Build a simple Django app with a UserProfile model and a signal that sends a notification after a profile is saved.Learn to set up signals properly and understand when signals are a good choice versus when to use direct function calls.
📋 What You'll Learn
Create a UserProfile model with fields user and bio
Add a boolean variable USE_SIGNALS to control if signals are active
Write a post-save signal handler that sends a notification when a profile is saved
Add a direct function call alternative to send notification without signals
💡 Why This Matters
🌍 Real World
Django signals help automate actions like sending emails or updating caches when database changes happen, without cluttering your main code.
💼 Career
Understanding when to use signals versus direct calls is important for writing maintainable Django apps and collaborating with teams.
Progress0 / 4 steps
1
Create the UserProfile model
Create a Django model called UserProfile with a user field as a OneToOneField to auth.User and a bio field as a TextField.
Django
Need a hint?

Use OneToOneField to link UserProfile to Django's User model.

2
Add a configuration variable to control signals
Add a boolean variable called USE_SIGNALS and set it to True to control whether signals should be active.
Django
Need a hint?

This variable will help you turn signals on or off easily.

3
Write a post-save signal handler to send notification
Write a Django post-save signal handler function called notify_profile_saved that sends a notification when a UserProfile instance is saved. Connect this handler to post_save for UserProfile only if USE_SIGNALS is True.
Django
Need a hint?

Use @receiver(post_save, sender=UserProfile) decorator and check USE_SIGNALS inside the handler.

4
Add a direct function call alternative without signals
Add a function called update_profile_bio that takes a UserProfile instance and a new bio string, updates the bio, saves the profile, and calls send_notification directly without using signals.
Django
Need a hint?

This function shows how to update and notify without relying on signals.