Combining Django Signals with Celery allows you to trigger background tasks in response to application events, such as saving a model or user registration. This ensures that long-running tasks don’t block user requests, improving application performance.
Django signals enable different parts of your application to communicate by triggering actions when certain events occur.
Celery is a distributed task queue system that runs time-consuming tasks asynchronously in the background.
Signals trigger Celery tasks so heavy operations are handled asynchronously.
# Install required packages
pip install celery redis
# celery configuration
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE','myproject.settings')
app=Celery('myproject')
app.config_from_object('django.conf:settings',namespace='CELERY')
app.autodiscover_tasks()
# background task
from celery import shared_task
@shared_task
def send_notification(user_email):
print(f"Notification sent to {user_email}")
# signal definition
from django.db.models.signals import post_save
from django.dispatch import receiver
from .tasks import send_notification
from .models import User
@receiver(post_save,sender=User)
def send_welcome_email(sender,instance,created,**kwargs):
if created:
send_notification.delay(instance.email)
Click the button below to observe how the Django (Main Thread) finishes quickly while Celery (Worker) handles the heavy task in the background.