通知是任何現代 Web 應用程式的關鍵組成部分,可確保使用者了解情況並參與其中。實施良好的通知系統可以處理多個管道,例如應用程式內警報、電子郵件和短信,同時動態自訂內容以實現無縫的用戶體驗。在本指南中,我們將引導您在 Django 中建立一個強大的、可擴展的通知系統。
系統功能
我們的通知系統旨在提供:
- 支援多管道:透過應用程式內提醒、電子郵件或簡訊發送通知。
- 動態內容個人化:帶有佔位符的模板,用於產生個人化訊息。
- 基於事件的觸發器:根據特定係統或使用者事件觸發通知。
- 狀態追蹤:監控電子郵件和簡訊通知的傳送狀態。
- 管理和系統整合:通知可以由管理員或系統事件觸發。
定義模型
1.通知範本
範本是我們系統的支柱,儲存可重複使用的通知內容。
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)
主要特點:
- 模板:帶有動態值佔位符的文本,例如 {{username}}.
- 頻道:指定是電子郵件、簡訊或應用程式內通知。
- trigger_event:將範本與特定事件關聯。
2.一般通知
通知模型將模板連結到使用者並儲存任何動態負載以進行個人化。
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)
3.特定於渠道的模型
為了獨特地處理電子郵件和短信,我們定義了特定的模型。
電子郵件通知
此模型管理特定於電子郵件的數據,例如動態訊息產生和傳遞追蹤。
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
簡訊通知
與電子郵件通知類似,這裡實現了簡訊特定邏輯。
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
管理整合
為了更輕鬆地管理通知,我們在 Django 管理面板中註冊模型。
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']
通知服務
我們將實作一個服務層來管理透過各種管道發送通知。
策略模式
使用策略模式,我們將為每個通知頻道定義類別。
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)
通知服務
該服務將所有內容連結在一起,根據通知管道選擇適當的策略。
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)
使用範例
以下是如何使用通知服務:
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
如果您發現本指南很有幫助且富有洞察力,請不要忘記點讚並關注以獲取更多此類內容。您的支持激勵我分享更多實用的實現和深入的教學。讓我們繼續一起建立令人驚嘆的應用程式!
以上是在 Django 中建立靈活的通知系統:綜合指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

選擇Python還是C 取決於項目需求:1)如果需要快速開發、數據處理和原型設計,選擇Python;2)如果需要高性能、低延遲和接近硬件的控制,選擇C 。

通過每天投入2小時的Python學習,可以有效提升編程技能。 1.學習新知識:閱讀文檔或觀看教程。 2.實踐:編寫代碼和完成練習。 3.複習:鞏固所學內容。 4.項目實踐:應用所學於實際項目中。這樣的結構化學習計劃能幫助你係統掌握Python並實現職業目標。

在兩小時內高效學習Python的方法包括:1.回顧基礎知識,確保熟悉Python的安裝和基本語法;2.理解Python的核心概念,如變量、列表、函數等;3.通過使用示例掌握基本和高級用法;4.學習常見錯誤與調試技巧;5.應用性能優化與最佳實踐,如使用列表推導式和遵循PEP8風格指南。

Python適合初學者和數據科學,C 適用於系統編程和遊戲開發。 1.Python簡潔易用,適用於數據科學和Web開發。 2.C 提供高性能和控制力,適用於遊戲開發和系統編程。選擇應基於項目需求和個人興趣。

Python更適合數據科學和快速開發,C 更適合高性能和系統編程。 1.Python語法簡潔,易於學習,適用於數據處理和科學計算。 2.C 語法複雜,但性能優越,常用於遊戲開發和系統編程。

每天投入兩小時學習Python是可行的。 1.學習新知識:用一小時學習新概念,如列表和字典。 2.實踐和練習:用一小時進行編程練習,如編寫小程序。通過合理規劃和堅持不懈,你可以在短時間內掌握Python的核心概念。

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3漢化版
中文版,非常好用

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SublimeText3 Linux新版
SublimeText3 Linux最新版

WebStorm Mac版
好用的JavaScript開發工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),