我已经在django开发了一段时间了,已经开发了一个整洁的网站,具有写博客,张贴问题,分享内容等功能。但是仍然缺少一件事,那就是为用户创建通知。
我想要做的是在他们的个人资料中通知用户,无论何时有人对他们的帖子发表评论,或者如果他们正在关注一个特定的帖子并有更新,然后通知用户该更新。我看了很多应用程序,但我仍然对如何做感到非常困惑。
在使用django-notification的情况下,我似乎有一个印象(这可能是错误的),我只能通过电子邮件通知用户,即我不能在用户配置文件中显示这些通知,就像我们在facebook上所做的那样。
首先我想知道我是否错了,然后我真的需要一些关于如何去做的适当的教程或指导。我知道如何注册通知并将其发送到适当的信号,但没有关于如何在模板中显示这些通知的文档,如果这可以做到的话。
任何指导/教程/入门文档都将深表感谢。
发布于 2011-12-22 20:15:06
是的,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'))现在,对于模板,非常简单。
模板/通知/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>模板/通知/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信号
以下是更多信息:
https://stackoverflow.com/questions/8603469
复制相似问题