我正在寻找访问拥有发布评论的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)
答案 0 :(得分: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)
解决此问题的另一种方法是创建将class
转换为role
的机制。但要做到这一点要困难得多,所以你可能不想这样做。