Django用户站内通知实现咨询及django-notification使用疑问
解决Django站内通知展示的问题
1. 纠正认知误区
你的认知是错误的,django-notifications-hd(原django-notification的活跃维护分支)完全支持像Facebook那样的站内通知展示,邮件只是它支持的多种通知渠道之一,核心功能本身就包含站内消息的存储与前端渲染能力。
2. 站内通知展示的核心实现步骤
你已经掌握了通过信号触发通知的环节,接下来只需要完成以下几步即可实现个人主页的通知展示:
2.1 在视图中获取用户通知
在个人主页的视图函数里,查询当前登录用户的通知数据:
from notifications.models import Notification def user_profile(request): # 获取当前用户的未读通知 unread_notifs = Notification.objects.unread().filter(recipient=request.user) # 获取当前用户的所有通知(按时间倒序) all_notifs = Notification.objects.filter(recipient=request.user).order_by('-timestamp') return render(request, 'profile.html', { 'unread_notifications': unread_notifs, 'all_notifications': all_notifs })
2.2 在模板中渲染通知列表
在个人主页模板profile.html中添加通知展示区域:
<!-- 未读通知角标 --> <div class="notif-header"> <a href="#notification-panel"> 通知 {% if unread_notifications.count > 0 %} <span class="badge">{{ unread_notifications.count }}</span> {% endif %} </a> </div> <!-- 通知列表面板 --> <div id="notification-panel" class="notification-list"> <h3>我的通知</h3> {% for notif in all_notifications %} <div class="notification-item {% if not notif.unread %}is-read{% endif %}"> <p>{{ notif.actor }} {{ notif.verb }} {{ notif.target }}</p> <small>{{ notif.timestamp|timesince }}前</small> {% if notif.unread %} <a href="{% url 'notifications:mark_as_read' notif.slug %}">标记已读</a> {% endif %} </div> {% empty %} <p>暂无通知</p> {% endfor %} </div>
2.3 配置已读标记路由
django-notifications-hd自带了标记通知为已读的视图,只需在项目urls.py中引入它的路由:
urlpatterns = [ # 其他路由 path('notifications/', include('notifications.urls', namespace='notifications')), ]
3. 核心概念与扩展技巧
- 核心模型字段:
Notification模型的actor(触发动作的用户)、verb(动作描述,比如"评论了")、target(被操作的内容,比如博客文章)、recipient(通知接收者)、unread(是否未读)等字段,足以支撑基础站内通知的展示逻辑。 - 自定义通知样式:如果需要区分不同类型的通知(比如评论、关注内容更新),可以通过
verb字段做条件判断:
{% for notif in all_notifications %} <div class="notification-item"> {% if notif.verb == "评论了你的文章" %} <i class="icon-comment"></i> {% elif notif.verb == "更新了你关注的内容" %} <i class="icon-refresh"></i> {% endif %} <p>{{ notif.actor }} {{ notif.verb }} {{ notif.target }}</p> </div> {% endfor %}
内容的提问来源于stack exchange,提问作者uxtepe
相关产品推荐
相关产品推荐

