2010-09-28 84 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