Home Backend Development Python Tutorial Building a Flexible Notification System in Django: A Comprehensive Guide

Building a Flexible Notification System in Django: A Comprehensive Guide

Dec 01, 2024 pm 03:43 PM

Building a Flexible Notification System in Django: A Comprehensive Guide

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.


System Features

Our notification system is designed to provide:

  1. Support for Multiple Channels: Notifications via in-app alerts, email, or SMS.
  2. Dynamic Content Personalization: Templates with placeholders to generate personalized messages.
  3. Event-Based Triggers: Trigger notifications based on specific system or user events.
  4. Status Tracking: Monitor the delivery status for email and SMS notifications.
  5. Admin and System Integration: Notifications can be triggered by administrators or system events.

Defining the Models

1. Notification Templates

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)
Copy after login
Copy after login

Key Features:

  • template: Text with placeholders for dynamic values like {{username}}.
  • channel: Specifies whether it’s an email, SMS, or in-app notification.
  • trigger_event: Associates the template with a specific event.

2. General Notifications

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)
Copy after login
Copy after login

3. Channel-Specific Models

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
Copy after login
Copy after login

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
Copy after login

Admin Integration

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']
Copy after login

Notification Service

We’ll implement a service layer to manage sending notifications through various channels.

Strategy Pattern

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)
Copy after login
Copy after login

Notification Service

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)
Copy after login
Copy after login

Usage Example

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
Copy after login
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles