Skip to content

Flash Sale Email Notification via Signals

This documentation explains the implementation of a Django signal that automatically triggers an email notification when a new Flash Sale is created.


Purpose

When a new FlashSale instance is created, an email is sent to all active users registered on the platform to notify them about the flash sale. The email includes both HTML and plain-text versions for compatibility.


How It Works

  1. Signal Trigger:

    • The post_save signal triggers when a FlashSale model instance is saved.
    • The created flag ensures the signal runs only for newly created instances, not updates.
  2. Email Content:

    • The render_to_string() function loads the email template flash_sale_template.html and renders it with the FlashSale instance data.
    • The strip_tags() function generates a plain-text version of the HTML email.
  3. Recipient Filtering:

    • The signal fetches all active users (is_active=True) from the User model.
    • Only users with valid email addresses are included.
  4. Sending Emails Asynchronously:

    • The signal uses a Celery task (send_email.delay) to send emails asynchronously.
    • This improves performance by offloading the email-sending process to a background worker.

Dependencies

  1. Celery Task:

    • The send_email function used here must be defined as a Celery task in accounts/tasks.py.
  2. Email Template:

    • A template file flash_sale_template.html must be created
  3. Settings Configuration:

    • Ensure your email backend and Celery configurations are properly set in settings.py.

Key Notes

  • The signal only sends emails for newly created flash sales.
  • Emails are sent asynchronously using Celery for better performance.

Summary

This implementation ensures that all active users are notified about new flash sales in real-time without blocking the main application flow. By leveraging Celery, the email-sending process runs smoothly in the background.


apps.py

The apps.py file ensures the signal is connected when the app is ready: