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.authorcarモデルがあり、コメントしている場合は、おそらく があります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です。しかし、それを正しく行うのははるかに難しいため、おそらくやりたくないでしょう。

于 2010-09-28T07:50:49.327 に答える