以下代码适用于评论部分。
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 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, 'friends_invite', context)
signals.post_save.connect(new_comment, sender=models.get_model('comments', 'Comment'))
但是当我们为其他客户模型评论实现相同的代码时,它会在输入模型中的记录时给出错误。
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("friends_invite", _("Invitation Received"), _("you have received an invitation"))
notification.create_notice_type("friends_accept", _("Acceptance Received"), _("an invitation you sent has been accepted"))
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 = {
'gufeed_feedcomment': instance,
}
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, 'friends_invite', context)
signals.post_save.connect(new_comment, sender=models.get_model('gufeed_feedcomment', 'FeedHottPoint'))
注意:我们正在收集已创建的friends_invite通知类型
错误: / gufeed / comment / add /中的AttributeError 'Manager'对象没有'for_model'属性