0
0
Djangoframework~5 mins

Receiver decorator in Django

Choose your learning style9 modes available
Introduction

The receiver decorator helps connect a function to a signal in Django. It makes your function run automatically when something happens.

You want to run code right after a user signs up.
You need to update related data when a model is saved.
You want to send a notification when a comment is posted.
You want to log actions automatically when certain events happen.
Syntax
Django
@receiver(signal, sender=SenderModel)
def function_name(sender, instance, **kwargs):
    # your code here
Use @receiver above your function to connect it to a signal.
The sender argument limits the signal to a specific model or source.
Examples
This runs my_handler after MyModel is saved.
Django
from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import MyModel

@receiver(post_save, sender=MyModel)
def my_handler(sender, instance, **kwargs):
    print(f"Saved: {instance}")
This runs migration_handler after migrations finish.
Django
from django.db.models.signals import post_migrate
from django.dispatch import receiver

@receiver(post_migrate)
def migration_handler(sender, **kwargs):
    print("Migration finished!")
Sample Program

This example prints a message every time a Book is saved.

Django
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

class Book(models.Model):
    title = models.CharField(max_length=100)

@receiver(post_save, sender=Book)
def announce_book_saved(sender, instance, **kwargs):
    print(f"Book saved: {instance.title}")
OutputSuccess
Important Notes

Remember to import receiver from django.dispatch.

Signals can slow down your app if overused, so use them wisely.

Summary

The receiver decorator links a function to a Django signal.

It helps run code automatically when events happen.

Use sender to specify which model or source triggers the function.