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
示例代碼:html
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)
示例代碼:python
from notifications.signals import notify notify.send(user, recipient=user, verb='消息內容')
若是但願在消息中攜帶額外的數據可參考下面的步驟
1.在項目的settings.py
文件配置數據庫
DJANGO_NOTIFICATIONS_CONFIG = { 'USE_JSONFIELD': True, }
2.發送消息時攜帶參數django
notify.send(instance.user, recipient=recipient, verb=verb, action_object=instance, url=url)
{% load notifications_tags %}
參考功能:post
1. 添加模板標籤 {% notifications_unread as unread_count %} 2. 使用:{{ unread_count }}
{% url 'notifications:mark_all_as_read' %}?next={% url 'userinfo' %} 不加next參數默認返回主路由,即'/'
功能不少,這裏就不一一舉例,具體可參考官方文檔。