Sobes.tech
Junior — Middle

What is the role and use of signals in the Django framework?

sobes.tech AI

Answer from AI

In Django, signals are used to implement the observer pattern, allowing application components to respond to certain events without tight coupling.

For example, when a new user is created, the post_save signal can automatically trigger a function that sends a welcome email.

Example of using a signal:

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User

@receiver(post_save, sender=User)
def send_welcome_email(sender, instance, created, **kwargs):
    if created:
        # email sending logic
        print(f"Sending email to user {instance.email}")

Thus, signals help separate the reaction logic to events from the main business logic, improving modularity and extensibility of the application.