如何使用django-notification通知用户有人评论他们的帖子

11 投票
1 回答
19638 浏览
提问于 2025-04-17 08:50

我已经在使用Django开发一段时间了,做了一个很不错的网站,功能包括写博客、发问、分享内容等等。不过,还有一件事我没做好,那就是给用户创建通知。

我想要做的是,当有人评论他们的帖子,或者他们关注的某个帖子有更新时,能够在他们的个人资料中通知他们。我查阅了很多应用,但还是对怎么实现这一点感到很困惑。

关于使用django-notification,我有一个印象(可能是错的),就是这个工具只能通过电子邮件通知用户,也就是说我不能像在Facebook那样在用户的个人资料中显示这些通知。

首先,我想知道我是不是错了,然后我真的需要一些合适的教程或指导,来帮助我实现这个功能。我知道怎么注册一个通知并在合适的信号下发送它,但没有文档说明如何在模板中显示这些通知,如果可以的话。

任何指导、教程或入门文档都将非常感谢。

1 个回答

13

是的,django-notifications 主要是用来发送邮件通知的。

这里有一个信号槽,你可以把它加到你的 models.py 文件里,然后根据自己的需要进行调整:

from django.db import models
from django.contrib.sites.models import Site
from django.db.models import signals
from notification import models as notification

def create_notice_types(app, created_models, verbosity, **kwargs):
    notification.create_notice_type("new_comment", "Comment posted", "A comment has been posted")
signals.post_syncdb.connect(create_notice_types, sender=notification)

def new_comment(sender, instance, created, **kwargs):
    # remove this if-block if you want notifications for comment edit too
    if not created:
        return None

    context = {
        'comment': instance,
        'site': Site.objects.get_current(),
    }
    recipients = []

    # add all users who commented the same object to recipients
    for comment in instance.__class__.objects.for_model(instance.content_object):
        if comment.user not in recipients and comment.user != instance.user:
            recipients.append(comment.user)

    # if the commented object is a user then notify him as well
    if isinstance(instance.content_object, models.get_model('auth', 'User')):
        # if he his the one who posts the comment then don't add him to recipients
        if instance.content_object != instance.user and instance.content_object not in recipients:
            recipients.append(instance.content_object)

    notification.send(recipients, 'new_comment', context)

signals.post_save.connect(new_comment, sender=models.get_model('comments', 'Comment'))

现在说说模板,这个很简单。

你可以在这个路径下找到模板:templates/notification/new_comment/short.txt

{{ comment.user }} commented on {{ comment.object }}

还有这个模板:templates/notification/new_comment/notice.html

<a href="{{ comment.user.get_absolute_url }}">{{ comment.user }}</a> commented <a href="{{ comment.content_object.get_absolute_url }}">{{ comment.content_object }}</a>

以及这个模板:templates/notification/new_comment/full.txt

{{ comment.user }} commented on {{ comment.content_object }}

Comment:
{{ comment.comment }}

Reply on: 
http://{{ site.domain }}{{ comment.content_object.get_absolute_url }}

注意:这只是我们生产代码的一个非常简化且未经测试的版本。

另外要提醒的是:Django-1.7 已经不再支持 post_syncdb 信号

这里还有一些额外的信息:

撰写回答