2010-09-28 48 views
1

我期待在访问谁拥有发布的评论的CONTENT_TYPEDjango的通知评论GET所有者

目前我可以访问用户谁帖子的用户,评论,但是我想通知谁拥有的人项目...

我试过user = comment.content_type.user但我得到一个错误。

在我的主要__init__.py文件

只要我改变,要user = request.user它工作正常,但随后的通知被发送到谁提出的意见的人。

from django.contrib.comments.signals import comment_was_posted 

if "notification" in settings.INSTALLED_APPS: 
    from notification import models as notification 

    def comment_notification(sender, comment, request, **kwargs): 
     subject = comment.content_object 
     for role in ['user']: 
      if hasattr(subject, role) and isinstance(getattr(subject, role), User): 
       user = getattr(subject, role) 
       message = comment 
       notification.send([user], "new_comment", {'message': message,}) 

    comment_was_posted.connect(comment_notification) 

回答

2

comment.content_object.user是正确的。但是这个问题很棘手。由于评论可以附加到任何模型,您不知道此模型是否有user字段。在许多情况下,可以有不同的名称,即。如果您对article有任何意见,文章可能有article.author和如果您有car模型,并且您正在评论它,可能会有car.owner。因此在这种情况下使用.user不适用于此目的。

我的命题来解决这个问题正在感兴趣的评论可能的角色的列表,并尝试将消息发送到所有的人:

from django.contrib.comments.signals import comment_was_posted 

if "notification" in settings.INSTALLED_APPS: 
    from notification import models as notification 

    def comment_notification(sender, comment, request, **kwargs): 
     subject = comment.content_object 
     for role in ['user', 'author', 'owner', 'creator', 'leader', 'maker', 'type any more']: 
     if hasattr(subject, role) and isinstance(getattr(subject, role), User): 
      user = getattr(subject, role) 
      message = comment 
      notification.send([user], "new_comment", {'message': message,}) 

    comment_was_posted.connect(comment_notification) 

你也应该,移动这个列表配置的某些王:

from django.contrib.comments.signals import comment_was_posted 
default_roles = ['user', 'author', 'owner'] 
_roles = settings.get('MYAPP_ROLES', default_roles) 
if "notification" in settings.INSTALLED_APPS: 
    from notification import models as notification 

    def comment_notification(sender, comment, request, **kwargs): 
     subject = comment.content_object 
     for role in _roles: 
     if hasattr(subject, role) and isinstance(getattr(subject, role), User): 
      user = getattr(subject, role) 
      message = comment 
      notification.send([user], "new_comment", {'message': message,}) 

    comment_was_posted.connect(comment_notification) 

另一种方法解决这个问题是创建机制转换classrole。但要让它变得更加困难很难,所以你可能不想这么做。

+0

首先感谢您的评论,只是想仔细检查一下你,你指的是content_object,虽然admin中只有一个content_type,所以我认为你是指那个呢? 我试过了上面的第一个代码,没有运气。它似乎通过,但没有通知实际上发送。我会用最新的代码更新我的问题。 – ApPeL 2010-09-28 08:12:05

+0

您应该阅读评论模型的描述:http://docs.djangoproject.com/en/1.2/ref/contrib/comments/models/。你是否从Django auth导入了User对象? – 2010-09-28 10:21:33