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
-
Signal Trigger:
- The
post_savesignal triggers when aFlashSalemodel instance is saved. - The
createdflag ensures the signal runs only for newly created instances, not updates.
- The
-
Email Content:
- The
render_to_string()function loads the email templateflash_sale_template.htmland renders it with theFlashSaleinstance data. - The
strip_tags()function generates a plain-text version of the HTML email.
- The
-
Recipient Filtering:
- The signal fetches all active users (
is_active=True) from theUsermodel. - Only users with valid email addresses are included.
- The signal fetches all active users (
-
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.
- The signal uses a Celery task (
Dependencies
-
Celery Task:
- The
send_emailfunction used here must be defined as a Celery task inaccounts/tasks.py.
- The
-
Email Template:
- A template file
flash_sale_template.htmlmust be created
- A template file
-
Settings Configuration:
- Ensure your email backend and Celery configurations are properly set in
settings.py.
- Ensure your email backend and Celery configurations are properly set in
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: