使用Django实现信号与消息通知系统【第154篇—Django】

👽发现宝藏

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。【点击进入巨牛的人工智能学习网站】。

使用Django实现信号与消息通知系统

在Web应用程序中,实现消息通知系统是至关重要的,它可以帮助用户及时了解到与其相关的事件或动态。Django提供了信号机制,可以用于实现这样的通知系统。本文将介绍如何使用Django的信号机制来构建一个简单但功能强大的消息通知系统,并提供相应的代码和实例。

1. 安装 Django

首先,确保你已经安装了 Django。你可以通过 pip 安装它:

pip install django

2. 创建 Django 项目和应用

创建一个 Django 项目,并在其中创建一个应用:

django-admin startproject notification_system
cd notification_system
python manage.py startapp notifications

3. 定义模型

notifications/models.py 文件中定义一个模型来存储通知信息:

from django.db import models
from django.contrib.auth.models import User

class Notification(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    message = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    read = models.BooleanField(default=False)

4. 创建信号

notifications/signals.py 文件中创建信号,该信号将在需要发送通知时触发:

from django.dispatch import Signal

notification_sent = Signal(providing_args=["user", "message"])

5. 编写信号处理器

notifications/handlers.py 文件中编写信号处理器,处理信号并创建相应的通知:

from django.dispatch import receiver
from .signals import notification_sent
from .models import Notification

@receiver(notification_sent)
def create_notification(sender, **kwargs):
    user = kwargs['user']
    message = kwargs['message']
    Notification.objects.create(user=user, message=message)

6. 发送通知

在你的应用程序中的适当位置,发送信号以触发通知:

from django.contrib.auth.models import User
from notifications.signals import notification_sent

# 例如,发送通知给特定用户
user = User.objects.get(username='username')
notification_sent.send(sender=None, user=user, message='你有一个新消息')

7. 显示通知

在你的应用程序中,可以通过查询通知模型来显示用户的通知:

from notifications.models import Notification

# 例如,在视图中查询并显示通知
def notifications_view(request):
    user_notifications = Notification.objects.filter(user=request.user)
    return render(request, 'notifications.html', {'notifications': user_notifications})

8. 标记通知为已读

当用户查看通知时,你可能需要将它们标记为已读。你可以在视图中执行此操作:

def mark_as_read(request, notification_id):
    notification = Notification.objects.get(pk=notification_id)
    notification.read = True
    notification.save()
    return redirect('notifications_view')

9. 定义通知模板

创建一个 HTML 模板来呈现通知信息。在 templates/notifications.html 文件中定义:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notifications</title>
</head>
<body>
    <h1>Notifications</h1>
    <ul>
        {% for notification in notifications %}
        <li{% if notification.read %} style="color: grey;"{% endif %}>
            {{ notification.message }}
            {% if not notification.read %}
            <a href="{% url 'mark_as_read' notification.id %}">Mark as Read</a>
            {% endif %}
        </li>
        {% endfor %}
    </ul>
</body>
</html>

10. 配置 URL

配置 URL 来处理通知相关的请求。在 notification_system/urls.py 文件中:

from django.urls import path
from notifications.views import notifications_view, mark_as_read

urlpatterns = [
    path('notifications/', notifications_view, name='notifications_view'),
    path('notifications/mark_as_read/<int:notification_id>/', mark_as_read, name='mark_as_read'),
]

11. 运行服务器

运行 Django 服务器以查看效果:

python manage.py runserver

现在,你可以访问 http://127.0.0.1:8000/notifications/ 查看通知页面,并且点击“标记为已读”链接来标记通知。

12. 集成前端框架

为了提升通知页面的用户体验,我们可以使用一些流行的前端框架来美化页面并添加一些交互功能。这里以Bootstrap为例。

首先,安装Bootstrap:

pip install django-bootstrap4

settings.py 中配置:

INSTALLED_APPS = [
    ...
    'bootstrap4',
    ...
]

修改通知模板 notifications.html,引入Bootstrap的样式和JavaScript文件,并使用Bootstrap的组件来美化页面:

{% load bootstrap4 %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notifications</title>
    {% bootstrap_css %}
</head>
<body>
    <div class="container">
        <h1 class="mt-5">Notifications</h1>
        <ul class="list-group mt-3">
            {% for notification in notifications %}
            <li class="list-group-item{% if notification.read %} list-group-item-light{% endif %}">
                {{ notification.message }}
                {% if not notification.read %}
                <a href="{% url 'mark_as_read' notification.id %}" class="btn btn-sm btn-primary ml-2">Mark as Read</a>
                {% endif %}
            </li>
            {% endfor %}
        </ul>
    </div>
    {% bootstrap_javascript %}
</body>
</html>

13. 使用 Ajax 实现标记为已读功能

我们可以使用 Ajax 技术来实现标记通知为已读的功能,这样可以避免刷新整个页面。修改模板文件和视图函数如下:

在模板中,使用 jQuery 来发送 Ajax 请求:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        $('.mark-as-read').click(function(e) {
            e.preventDefault();
            var url = $(this).attr('href');
            $.ajax({
                type: 'GET',
                url: url,
                success: function(data) {
                    if (data.success) {
                        window.location.reload();
                    }
                }
            });
        });
    });
</script>

修改视图函数 mark_as_read

from django.http import JsonResponse

def mark_as_read(request, notification_id):
    notification = Notification.objects.get(pk=notification_id)
    notification.read = True
    notification.save()
    return JsonResponse({'success': True})

14. 添加通知计数功能

为了让用户可以清晰地知道有多少未读通知,我们可以添加一个通知计数的功能,将未读通知的数量显示在页面上。

首先,在 notifications/views.py 中修改 notifications_view 视图函数:

def notifications_view(request):
    user_notifications = Notification.objects.filter(user=request.user)
    unread_count = user_notifications.filter(read=False).count()
    return render(request, 'notifications.html', {'notifications': user_notifications, 'unread_count': unread_count})

然后,在通知模板中显示未读通知的数量:

<div class="container">
    <h1 class="mt-5">Notifications</h1>
    <div class="alert alert-info mt-3" role="alert">
        You have {{ unread_count }} unread notification(s).
    </div>
    <ul class="list-group mt-3">
        {% for notification in notifications %}
        <li class="list-group-item{% if notification.read %} list-group-item-light{% endif %}">
            {{ notification.message }}
            {% if not notification.read %}
            <a href="{% url 'mark_as_read' notification.id %}" class="btn btn-sm btn-primary ml-2 mark-as-read">Mark as Read</a>
            {% endif %}
        </li>
        {% endfor %}
    </ul>
</div>

15. 实时更新通知计数

为了使通知计数实时更新,我们可以使用 Ajax 技术定期请求服务器以获取最新的未读通知数量。

在通知模板中添加 JavaScript 代码:

<script>
    function updateUnreadCount() {
        $.ajax({
            type: 'GET',
            url: '{% url "unread_count" %}',
            success: function(data) {
                $('#unread-count').text(data.unread_count);
            }
        });
    }
    $(document).ready(function() {
        setInterval(updateUnreadCount, 5000); // 每5秒更新一次
    });
</script>

notifications/urls.py 中添加一个新的 URL 路由来处理未读通知数量的请求:

from django.urls import path
from .views import notifications_view, mark_as_read, unread_count

urlpatterns = [
    path('notifications/', notifications_view, name='notifications_view'),
    path('notifications/mark_as_read/<int:notification_id>/', mark_as_read, name='mark_as_read'),
    path('notifications/unread_count/', unread_count, name='unread_count'),
]

最后,在 notifications/views.py 中定义 unread_count 视图函数:

from django.http import JsonResponse

def unread_count(request):
    user_notifications = Notification.objects.filter(user=request.user, read=False)
    unread_count = user_notifications.count()
    return JsonResponse({'unread_count': unread_count})

16. 添加通知删除功能

除了标记通知为已读之外,有时用户还可能希望能够删除一些通知,特别是一些不再需要的通知。因此,我们可以添加一个删除通知的功能。

首先,在模板中为每个通知添加一个删除按钮:

<ul class="list-group mt-3">
    {% for notification in notifications %}
    <li class="list-group-item{% if notification.read %} list-group-item-light{% endif %}">
        {{ notification.message }}
        <div class="btn-group float-right" role="group" aria-label="Actions">
            {% if not notification.read %}
            <a href="{% url 'mark_as_read' notification.id %}" class="btn btn-sm btn-primary mark-as-read">Mark as Read</a>
            {% endif %}
            <a href="{% url 'delete_notification' notification.id %}" class="btn btn-sm btn-danger delete-notification">Delete</a>
        </div>
    </li>
    {% endfor %}
</ul>

然后,在 notifications/urls.py 中添加一个新的 URL 路由来处理删除通知的请求:

urlpatterns = [
    ...
    path('notifications/delete/<int:notification_id>/', delete_notification, name='delete_notification'),
]

接着,在 notifications/views.py 中定义 delete_notification 视图函数:

def delete_notification(request, notification_id):
    notification = Notification.objects.get(pk=notification_id)
    notification.delete()
    return redirect('notifications_view')

最后,为了使用户可以通过 Ajax 删除通知,我们可以修改模板中的 JavaScript 代码:

<script>
    $(document).ready(function() {
        $('.delete-notification').click(function(e) {
            e.preventDefault();
            var url = $(this).attr('href');
            $.ajax({
                type: 'GET',
                url: url,
                success: function(data) {
                    if (data.success) {
                        window.location.reload();
                    }
                }
            });
        });
    });
</script>

17. 添加异步任务处理

在实际应用中,通知系统可能需要处理大量的通知,而生成和发送通知可能是一个耗时的操作。为了避免阻塞用户请求,我们可以使用异步任务处理来处理通知的生成和发送。

17.1 安装 Celery

首先,安装 Celery 和 Redis 作为消息代理:

pip install celery redis
17.2 配置 Celery

在 Django 项目的根目录下创建一个名为 celery.py 的文件,并添加以下内容:

import os
from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'notification_system.settings')

app = Celery('notification_system')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

settings.py 中添加 Celery 配置:

CELERY_BROKER_URL = 'redis://localhost:6379/0'
17.3 创建异步任务

notifications/tasks.py 中定义异步任务来处理通知的生成和发送:

from celery import shared_task
from .models import Notification

@shared_task
def send_notification(user_id, message):
    user = User.objects.get(pk=user_id)
    Notification.objects.create(user=user, message=message)
17.4 触发异步任务

在你的应用程序中,当需要发送通知时,使用 Celery 的 delay() 方法触发异步任务:

from notifications.tasks import send_notification

send_notification.delay(user_id, '你有一个新消息')

总结:

本文介绍了如何使用 Django 构建一个功能强大的消息通知系统,其中涵盖了以下主要内容:

  1. 通过定义模型、创建信号、编写信号处理器,实现了通知系统的基本框架。
  2. 集成了前端框架 Bootstrap,并使用 Ajax 技术实现了标记通知为已读的功能,以及实时更新未读通知数量的功能,提升了用户体验。
  3. 添加了通知删除功能,使用户可以更灵活地管理通知。
  4. 引入了异步任务处理技术 Celery,将通知的生成和发送操作转换为异步任务,提高了系统的性能和响应速度。

通过这些步骤,我们建立了一个功能完善的消息通知系统,用户可以及时了解到与其相关的重要信息,并且可以自由地管理和处理通知,从而增强了应用的交互性、可用性和性能。

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/485818.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【JAVA】数组的定义和使用

JAVA的数组和c语言的相似但是在创建上略有不同 数组的创建及初始化 T[] 数组名 new T[N]; T&#xff1a;表示数组中存放元素的类型 T[]&#xff1a;表示数组的类型 N&#xff1a;表示数组的长度 动态初始化 int[] array new int[10]; 静态初始化 int[] array1 new …

边缘计算基础介绍及AKamai-linode产品分析

1、背景 随着互联网的发展&#xff0c;我们进入了大数据时代&#xff0c;这个时代也是移动互联网的时代&#xff0c;而且这个时代&#xff0c;大量的线下服务走到线上&#xff0c;随之而来的&#xff0c;比如外卖、叫车……于是&#xff0c;有各种各样的 App 和设备在收集你的…

基于DWT(离散小波变换)的图像水印算法,Matlab实现

博主简介&#xff1a; 专注、专一于Matlab图像处理学习、交流&#xff0c;matlab图像代码代做/项目合作可以联系&#xff08;QQ:3249726188&#xff09; 个人主页&#xff1a;Matlab_ImagePro-CSDN博客 原则&#xff1a;代码均由本人编写完成&#xff0c;非中介&#xff0c;提供…

nodejs+vue高校师资管理系统python-flask-django-php

快速发展的社会中&#xff0c;人们的生活水平都在提高&#xff0c;生活节奏也在逐渐加快。为了节省时间和提高工作效率&#xff0c;越来越多的人选择利用互联网进行线上打理各种事务&#xff0c;然后线上管理系统也就相继涌现。与此同时&#xff0c;人们开始接受方便的生活方式…

nginx: [emerg] stream directive is duplicate in /etc/nginx/nginx.conf:56

背景&#xff1a; 在维护paas平台的时候发现一个web前端容器服务运行报错&#xff0c;提示如下&#xff1a; 问题分析&#xff1a; 根据日志的内容&#xff0c;发现是nginx.conf配置文件的stream模块配置存在问题导致的。需要查看一下nginx.conf配置文件的内容&#xff1a; 注…

Soybean Admin:基于 Vue3、Vite3、TypeScript、NaiveUI、Pinia 和 UnoCSS 的清新优雅的中后台模版

一、引言 随着互联网技术的快速发展&#xff0c;前端开发领域也在不断演进。Soybean Admin 作为一个基于最新前端技术栈的中后台模版&#xff0c;为开发者提供了一个高效、规范、灵活的解决方案。本文将深入探讨 Soybean Admin 的技术特性及其在中后台前端开发中的优势。 二、…

android h5理财(记账)管理系统eclipse开发mysql数据库编程服务端java计算机程序设计

一、源码特点 android h5理财管理系统是一套完善的WEBandroid设计系统&#xff0c;对理解JSP java&#xff0c;安卓app编程开发语言有帮助&#xff08;系统采用web服务端APP端 综合模式进行设计开发&#xff09;&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要…

从零开始的 dbt 入门教程 (dbt cloud 自动化篇)

一、引 在前面的几篇文章中&#xff0c;我们从 dbt core 聊到了 dbt 项目工程化&#xff0c;我相信前几篇文章足够各位数据开发师从零快速入门 dbt 开发&#xff0c;那么到现在我们更迫切需要解决的是如何让数据更新做到定时化&#xff0c;毕竟作为开发我们肯定没有经历每天定…

基于springboot实现在线拍卖系统项目【项目源码+论文说明】计算机毕业设计

基于springboot实现在线拍卖系统演示 摘要 随着社会的发展&#xff0c;社会的各行各业都在利用信息化时代的优势。计算机的优势和普及使得各种信息系统的开发成为必需。 在线拍卖系统&#xff0c;主要的模块包括管理员&#xff1b;首页、个人中心、用户管理、商品类型管理、拍…

[热门]通义灵码做活动,送挺多礼品,快来薅羊毛!!!

你的编辑器装上智能ai编辑了吗&#xff0c;的确挺好用的。 最近阿里云AI编码搞活动&#xff0c;可以免费体验并且还可以抽盲盒。有日历、马克杯、代金券、等等其他数码产品。 大多数都是日历。 点击链接参与「通义灵码 体验 AI 编码&#xff0c;开 AI 盲盒」 https://develope…

PCI产业概述和产业发展动态分享

atsec白海蔚 2024年3月底 关键词&#xff1a;支付卡产业、PCI DSS、数据安全、支付交易 本文为atsec和作者技术共享类文章&#xff0c;旨在共同探讨信息安全的相关话题。转载请注明&#xff1a;atsec和作者名称。 *如有兴趣了解早期产业信息请参见作者于2021年4月发布信息&a…

液晶显示解决方案T-CON面板显示驱动PMIC芯片

随着数智时代的到来&#xff0c;高清电影、游戏、VR/AR、车载等对多屏、大尺寸、更清晰显示设备的需求越来越高&#xff1b;特别是在智能手机、平板电脑、电视、广告展示和显示器等消费电子产品领域&#xff1b;高效、稳定、多功能的电源管理芯片变得至关重要。 对于LCD TV显示…

Linux-安装redis

安装指令 sudo apt-get install redis-server 启动服务 sudo systemctl start redis 查找redis路径 find / -name "filename" linux redis修改密码 sudo nano /etc/redis/redis.conf 找到 "requirepass" 这一行&#xff0c;取消注释并设置新的密码&…

算法练习-常用查找算法复现

一个不知名大学生&#xff0c;江湖人称菜狗 original author: Jacky Li Email : 3435673055qq.com Time of completion&#xff1a;2024.03.24 Last edited: 2024.03.24 目录 算法练习-常用查找算法复现 第1关&#xff1a;顺序查找&#xff08;算法7.1和7.2&#xff09; 任务…

第二十章 TypeScript(webpack构建ts+vue3项目)

构建项目目录 src-- main.ts-- App.vue--shim.d.tswebpack.config.jsindex.htmlpackage.jsontsconfig.json 基础构建 npm install webpack -D npm install webpack-dev-server -D npm install webpack-cli -D package.json 添加打包命令和 启动服务的命令 {"scripts…

使用PySimpleGUI库打造一款轻量级计算器

目录 一、PySimpleGUI简介 二、安装PySimpleGUI 三、创建计算器界面 四、实现计算器的功能 五、总结 在Python的世界中&#xff0c;GUI&#xff08;图形用户界面&#xff09;库的选择多种多样&#xff0c;但如果你是一个新手&#xff0c;或者想要快速且简单地创建一个G…

谷粒商城——Redisson看门狗

可重入锁&#xff1a; 看门狗机制&#xff1a;(lock.lock()不设置过期时间就会自动触发 看门狗机制) 如果一个线程已经上锁后&#xff0c;在运行的过程中中断导致未释放锁从而导致其他线程无法进行&#xff0c;为此需要为每个锁设置自动过期时间。但是如果线程运行时间较长&am…

网线相关(T568A和T568B定义,交叉线连接方式,8芯网线1分2)

T568B 1 2 3 4 5 6 7 8 白橙 橙 白绿 蓝 白蓝 绿 白棕 棕 T568A 1 2 3 4 5 6 …

智慧园区整体解决方案

智慧园区整体解决方案-综合运营管理系统 1. 园区现状与发展机遇 2. 智慧园区愿景 3. 智慧解决方案架构 4. 智慧园区各子系统介绍 5. 智慧园区建设意义 楼宇管理&#xff0c;物业管理&#xff0c;消防管理&#xff0c;巡检管理&#xff0c;门禁管理&#xff0c;停车管理等综合实…

Linux命令dmesg详解和实例: 显示或控制内核环形缓冲区的内容,查看或操作内核消息

目录 一、命令介绍 二、 基本用法 1、语法结构 2、选项 3、支持的日志设施&#xff1a; 4、支持的日志级别(优先级)&#xff1a; 四、基本用法 1. 查看内核消息&#xff1a; 2. 实时查看内核消息&#xff1a; 3. 清空内核消息&#xff1a; 五、 高级用法 1. 过滤消…
最新文章