一、安装
pip install django-notifications-hq
二、配置
1. settings.py 文件
INSTALLED_APPS = (
'django.contrib.auth',
...
'notifications',
...
)
2. 项目 urls.py 文件
import notifications.urls
urlpatterns = [
...
url('^inbox/notifications/', include(notifications.urls, namespace='notifications')),
...
]
三、数据库迁移
python manage.py migrate notifications
四、使用
- 一般生成的通知最好在单独的信号中完成,Django 有自带的信号处理方式,具体可参考 Django 官方文档 signals 章节
示例代码:
from django.dispatch import receiver
from django.db.models.signals import post_save
from comment.models import Comment
from notifications.signals import notify
from django.utils.html import strip_tags
@receiver(post_save, sender=Comment)
def send_notification(sender, instance, **kwargs):
# 发送站内消息
if instance.reply_to is None:
# 评论
recipient = instance.content_object.get_user()
if instance.content_type.model == 'blog':
blog = instance.content_object
verb = '{0} 评论了你的博客《{1}》'.format(instance.user.username, blog.title)
else:
raise Exception('unkown comment object type')
else:
# 回复
recipient = instance.reply_to
verb = '{0} 回复了你的评论“{1}”'.format(
instance.user.username,
strip_tags(instance.parent.text)
)
notify.send(instance.user, recipient=recipient, verb=verb, action_object=instance)
- 也可在项目任何地方生成通知
示例代码:
from notifications.signals import notify
notify.send(user, recipient=user, verb='消息内容')
-
如果希望在消息中携带额外的数据可参考下面的步骤
1. 在项目的settings.py
文件配置DJANGO_NOTIFICATIONS_CONFIG = {'USE_JSONFIELD': True,}
2. 发送消息时携带参数
notify.send(instance.user, recipient=recipient, verb=verb, action_object=instance, url=url)
五、在 HTML 模板页面渲染
- 在页面顶部添加模板标签
{% load notifications_tags %}
-
参考功能:
- 获取未读数量
1. 添加模板标签 {% notifications_unread as unread_count %} 2. 使用:{{unread_count}}
- 全部标记为已读
{% url 'notifications:mark_all_as_read' %}?next={% url 'userinfo' %} 不加 next 参数默认返回主路由,即 '/'
功能很多,这里就不一一举例,具体可参考官方文档。