Django:Mark as Read" Notifications"

时间:2017-09-15 21:31:18

标签: python django

我正在做一个学校项目。现在任何用户都可以提问。

为了在任何用户提出问题时通知所有用户我已经创建了一个新应用&通过简单的观点通知他们。无论什么时候提出问题。但它只是普通的通知。

用户打开“通知”标签后,如何将其标记为已读?就像在社交网络上一样!

1 个答案:

答案 0 :(得分:1)

我建议您使用ContentType为任何模型制作动态通知。下面的代码段是如何实施 通知系统 ;

的示例

<强> 1。在models.py

from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.utils.translation import ugettext_lazy as _


class ContentTypeToGetModel(object):

    """
    requires fields:
        - content_type: FK(ContentType)
        - object_id: PositiveIntegerField()
    """

    def get_related_object(self):
        """
        return the related object of content_type.
        eg: <Question: Holisticly grow synergistic best practices>
        """
        # This should return an error: MultipleObjectsReturned
        # return self.content_type.get_object_for_this_type()
        # So, i handle it with this one:
        model_class = self.content_type.model_class()
        return model_class.objects.get(id=self.object_id)

    @property
    def _model_name(self):
        """
        return lowercase of model name.
        eg: `question`, `answer`
        """
        return self.get_related_object()._meta.model_name


class Notification(models.Model, ContentTypeToGetModel):
    # sender = models.ForeignKey(
    #    User, related_name='notification_sender')

    receiver = models.ForeignKey(
        User, related_name='notification_receiver')

    content_type = models.ForeignKey(
        ContentType, related_name='notifications', on_delete=models.CASCADE)

    object_id = models.PositiveIntegerField(_('Object id'))
    content_object = GenericForeignKey('content_type', 'object_id')

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    STATUS_CHOICES = (
        ('reply', _('a reply')),
        ('comment', _('a comment')),
        ('message', _('a message'))
    )
    status = models.CharField(
        _('Status'), max_length=20,
        choices=STATUS_CHOICES, default='comment')

    is_read = models.BooleanField(
        _('Is read?'), default=False)

    def __str__(self):
        title = _('%(receiver)s have a %(status)s in the %(model)s:%(id)s')
        return title % {'receiver': self.receiver.username, 'status': self.status,
                        'model': self._model_name, 'id': self.object_id}

    class Meta:
        verbose_name_plural = _('notifications')
        ordering = ['-created']

<强> 2。在views.py

from django.views.generic import (ListView, DetailView)
from yourapp.models import Notification


class NotificationListView(ListView):
    model = Notification
    context_object_name = 'notifications'
    paginate_by = 10
    template_name = 'yourapp/notifications.html'

    def get_queryset(self):
        notifications = self.model.objects.filter(receiver=self.request.user)

        # mark as reads if `user` is visit on this page.
        notifications.update(is_read=True)
        return notifications

第3。在yourapp/notifications.html

{% extends "base.html" %}

{% for notif in notifications %}
  {{ notif }}

  {# for specific is like below #}
  {# `specific_model_name` eg: `comment`, `message`, `post` #}
  {% if notif._model_name == 'specific_model_name' %}
    {# do_stuff #}
  {% endif %}
{% endfor %}
  

那么,当我创建通知时?   例如:当其他用户在此帖子上向receiver发送评论时。

from django.contrib.contenttypes.models import ContentType

def send_a_comment(request):
    if request.method == 'POST':
        form = SendCommentForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            #instance.sender = request.user
            ...
            instance.save()

            receiver = User.objects.filter(email=instance.email).first()
            content_type = ContentType.objects.get(model='comment')

            notif = Notification.objects.create(
                receiver=receiver,
                #sender=request.user,
                content_type=content_type,
                object_id=instance.id,
                status='comment'
            )
            notif.save()
  

菜单 怎么样?喜欢这个stackoverflow,facebook,Instagram,还是其他?

您可以使用templatetags处理它,例如:

# yourapp/templatetags/notification_tags.py

from django import template

from yourapp.models import Notification

register = template.Library()

@register.filter
def has_unread_notif(user):
    notifications = Notification.objects.filter(receiver=user, is_read=False)
    if notifications.exists():
        return True
    return False

navs.html菜单:

{% load notification_tags %}

{% if request.user.is_authenticated %}
  <ul class="authenticated-menu">
    <li>
        <a href="/notifications/">
          {% if request.user|has_unread_notif %}
            <i class="globe red active icon"></i>
          {% else %}
            <i class="globe icon"></i>
          {% endif %}
        </a>
    </li>
  </ul>
{% endif %}