1

我正在考虑访问拥有已发布评论的 content_type 的用户

目前我可以访问发布评论的用户,但是我想通知拥有该项目的人......

我试着做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)
4

1 回答 1

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. 但要做到这一点要困难得多,所以你可能不想这样做。

于 2010-09-28T07:50:49.327 回答