Notifications are a key component of any modern web application, ensuring users are informed and engaged. A well-implemented notification system can handle multiple channels like in-app alerts, emails, and SMS while dynamically tailoring content for a seamless user experience. In this guide, we’ll walk you through creating a robust, scalable notification system in Django.
Our notification system is designed to provide:
Templates act as the backbone of our system, storing reusable content for notifications.
from django.db import models class ChannelType(models.TextChoices): APP = 'APP', 'In-App Notification' SMS = 'SMS', 'SMS' EMAIL = 'EMAIL', 'Email' class TriggeredByType(models.TextChoices): SYSTEM = 'SYSTEM', 'System Notification' ADMIN = 'ADMIN', 'Admin Notification' class TriggerEvent(models.TextChoices): ENROLLMENT = 'ENROLLMENT', 'Enrollment' ANNOUNCEMENT = 'ANNOUNCEMENT', 'Announcement' PROMOTIONAL = 'PROMOTIONAL', 'Promotional' RESET_PASSWORD = 'RESET_PASSWORD', 'Reset Password' class NotificationTemplate(models.Model): title = models.CharField(max_length=255) template = models.TextField(help_text='Use placeholders like {{username}} for personalization.') channel = models.CharField(max_length=20, choices=ChannelType.choices, default=ChannelType.APP) triggered_by = models.CharField(max_length=20, choices=TriggeredByType.choices, default=TriggeredByType.SYSTEM) trigger_event = models.CharField(max_length=50, choices=TriggerEvent.choices, help_text='Event that triggers this template.') is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
Key Features:
The Notification model links templates to users and stores any dynamic payload for personalization.
class Notification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="notifications") content = models.ForeignKey(NotificationTemplate, on_delete=models.CASCADE, related_name="notifications") payload = models.JSONField(default=dict, help_text="Data to replace template placeholders.") is_read = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True)
To handle emails and SMS uniquely, we define specific models.
Email Notifications
This model manages email-specific data, such as dynamic message generation and delivery tracking.
class StatusType(models.TextChoices): PENDING = 'PENDING', 'Pending' SUCCESS = 'SUCCESS', 'Success' FAILED = 'FAILED', 'Failed' class EmailNotification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='email_notifications') content = models.ForeignKey(NotificationTemplate, on_delete=models.CASCADE, related_name='email_notifications') payload = models.JSONField(default=dict) status = models.CharField(max_length=20, choices=StatusType.choices, default=StatusType.PENDING) status_reason = models.TextField(null=True) @property def email_content(self): """ Populate the template with dynamic data from the payload. """ content = self.content.template for key, value in self.payload.items(): content = re.sub( rf"{{{{\s*{key}\s*}}}}", str(value), content, ) return content
SMS Notifications
Similar to email notifications, SMS-specific logic is implemented here.
class SMSNotification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sms_notifications') content = models.ForeignKey(NotificationTemplate, on_delete=models.CASCADE, related_name='sms_notifications') payload = models.JSONField(default=dict) status = models.CharField(max_length=20, choices=StatusType.choices, default=StatusType.PENDING) status_reason = models.TextField(null=True) @property def sms_content(self): """ Populate the template with dynamic data from the payload. """ content = self.content.template for key, value in self.payload.items(): content = re.sub( rf"{{{{\s*{key}\s*}}}}", str(value), content, ) return content
To make managing notifications easier, we register the models in the Django admin panel.
from django.contrib import admin from notifier.models import NotificationTemplate @admin.register(NotificationTemplate) class NotificationTemplateAdmin(admin.ModelAdmin): list_display = ['title', 'channel', 'triggered_by', 'trigger_event', 'is_active'] list_filter = ['channel', 'triggered_by', 'is_active'] search_fields = ['title', 'trigger_event']
We’ll implement a service layer to manage sending notifications through various channels.
Using the Strategy Pattern, we’ll define classes for each notification channel.
from django.db import models class ChannelType(models.TextChoices): APP = 'APP', 'In-App Notification' SMS = 'SMS', 'SMS' EMAIL = 'EMAIL', 'Email' class TriggeredByType(models.TextChoices): SYSTEM = 'SYSTEM', 'System Notification' ADMIN = 'ADMIN', 'Admin Notification' class TriggerEvent(models.TextChoices): ENROLLMENT = 'ENROLLMENT', 'Enrollment' ANNOUNCEMENT = 'ANNOUNCEMENT', 'Announcement' PROMOTIONAL = 'PROMOTIONAL', 'Promotional' RESET_PASSWORD = 'RESET_PASSWORD', 'Reset Password' class NotificationTemplate(models.Model): title = models.CharField(max_length=255) template = models.TextField(help_text='Use placeholders like {{username}} for personalization.') channel = models.CharField(max_length=20, choices=ChannelType.choices, default=ChannelType.APP) triggered_by = models.CharField(max_length=20, choices=TriggeredByType.choices, default=TriggeredByType.SYSTEM) trigger_event = models.CharField(max_length=50, choices=TriggerEvent.choices, help_text='Event that triggers this template.') is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
This service ties everything together, selecting the appropriate strategy based on the notification channel.
class Notification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="notifications") content = models.ForeignKey(NotificationTemplate, on_delete=models.CASCADE, related_name="notifications") payload = models.JSONField(default=dict, help_text="Data to replace template placeholders.") is_read = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True)
Here’s how you can use the notification service:
class StatusType(models.TextChoices): PENDING = 'PENDING', 'Pending' SUCCESS = 'SUCCESS', 'Success' FAILED = 'FAILED', 'Failed' class EmailNotification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='email_notifications') content = models.ForeignKey(NotificationTemplate, on_delete=models.CASCADE, related_name='email_notifications') payload = models.JSONField(default=dict) status = models.CharField(max_length=20, choices=StatusType.choices, default=StatusType.PENDING) status_reason = models.TextField(null=True) @property def email_content(self): """ Populate the template with dynamic data from the payload. """ content = self.content.template for key, value in self.payload.items(): content = re.sub( rf"{{{{\s*{key}\s*}}}}", str(value), content, ) return content
If you found this guide helpful and insightful, don’t forget to like and follow for more content like this. Your support motivates me to share more practical implementations and in-depth tutorials. Let’s keep building amazing applications together!
The above is the detailed content of Building a Flexible Notification System in Django: A Comprehensive Guide. For more information, please follow other related articles on the PHP Chinese website!