What are Django signals and give an example of how they can be used in a Django application?

1 Answers
Answered by suresh

What are Django signals and how to use them in a Django application?

What are Django signals and how to use them in a Django application?

Django signals allow decoupled applications to get notified when certain actions occur elsewhere in the application. This helps in achieving loose coupling and allows different parts of the application to communicate without having direct dependencies on each other.

Example of using Django signals in a Django application:

Suppose we want to send an email notification to users whenever a new post is created in our Django application. We can use Django signals to achieve this functionality seamlessly.


  from django.db.models.signals import post_save
  from django.dispatch import receiver
  from django.core.mail import send_mail
  from myapp.models import Post

  @receiver(post_save, sender=Post)
  def send_new_post_notification(sender, instance, **kwargs):
      subject = 'New Post Created'
      message = f'A new post titled "{instance.title}" has been created.'
      send_mail(subject, message, 'admin@example.com', [user.email for user in User.objects.all()])
  

In this example, whenever a new Post object is saved, the send_new_post_notification function gets called automatically and sends an email notification to all users.

Answer for Question: What are Django signals and give an example of how they can be used in a Django application?