当海报收到通知后,功能会通知评论者 [英] Function notifies commentor when the poster should get notified

查看:146
本文介绍了当海报收到通知后,功能会通知评论者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我对a的帖子发表评论,那么我会收到一条通知,表示我对a发表了评论,但通知系统应通知用户谁创建了a。

If I comment on the post named "a", then I get a notification saying that I made the comment on "a" but the notification system should notify the user who created post "a".

我有一个线索,做什么,因为我已经做了类似的事情(通知用户谁有评论的时候有一个答复的评论)感谢一些教程。

I have a clue what to do, because I have done something similar (notifying the user who commented when there's a reply to that comment) thanks to some tutorial.

在models.py通知中,我必须发送正确的通知并连接到它。我会发布我的完整代码,您可以看到连接的底部功能,这是我遇到的问题。

In models.py for notification, I have to send the right notification and connect to it. I'll post my full code, you can see the bottom function for the connecting, and this is the one I'm having problem with.

    from django.conf import settings
    from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
    from django.contrib.contenttypes.models import ContentType
    from django.core.urlresolvers import reverse
    from django.db import models
    from django.contrib.auth.models import User

    from main.models import Post
    from accounts.models import MyProfile
    from .signals import notify
    # Create your models here.

    class NotificationQuerySet(models.query.QuerySet):
        def get_user(self, recipient):
            return self.filter(recipient=recipient)

        def mark_targetless(self, recipient):
            qs = self.unread().get_user(recipient)
            qs_no_target = qs.filter(target_object_id=None)
            if qs_no_target:
                qs_no_target.update(read=True)

        def mark_all_read(self, recipient):
            qs = self.unread().get_user(recipient)
            qs.update(read=True)

        def mark_all_unread(self, recipient):
            qs = self.read().get_user(recipient)
            qs.update(read=False)

        def unread(self):
            return self.filter(read=False)

        def read(self):
            return self.filter(read=True)

        def recent(self):
            return self.unread()[:5]


    class NotificationManager(models.Manager):
        def get_queryset(self):
            return NotificationQuerySet(self.model, using=self._db)

        def all_unread(self, user):
            return self.get_queryset().get_user(user).unread()

        def all_read(self, user):
            return self.get_queryset().get_user(user).read()

        def all_for_user(self, user):
            self.get_queryset().mark_targetless(user)
            return self.get_queryset().get_user(user)


    class Notification(models.Model):
        sender_content_type = models.ForeignKey(ContentType, related_name='nofity_sender')
        sender_object_id = models.PositiveIntegerField()
        sender_object = GenericForeignKey("sender_content_type", "sender_object_id")

        verb = models.CharField(max_length=255)

        action_content_type = models.ForeignKey(ContentType, related_name='notify_action', 
            null=True, blank=True)
        action_object_id = models.PositiveIntegerField(null=True, blank=True)
        action_object = GenericForeignKey("action_content_type", "action_object_id")

        target_content_type = models.ForeignKey(ContentType, related_name='notify_target', 
            null=True, blank=True)
        target_object_id = models.PositiveIntegerField(null=True, blank=True)
        target_object = GenericForeignKey("target_content_type", "target_object_id")

        recipient = models.ForeignKey(settings.AUTH_PROFILE_MODULE, related_name='notifications')
        read = models.BooleanField(default=False)
        timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

        objects = NotificationManager()



        def __unicode__(self):
            try:
                target_url = self.target_object.get_absolute_url()
            except:
                target_url = None
            context = {
                "sender": self.sender_object,
                "verb": self.verb,
                "action": self.action_object,
                "target": self.target_object,
                "verify_read": reverse("notifications_read", kwargs={"id": self.id}),
                "target_url": target_url,
            }
            if self.target_object:
                if self.action_object and target_url:
                    return "%(sender)s %(verb)s <a href='%(verify_read)s?next=%(target_url)s'>%(target)s</a> with %(action)s" %context
                if self.action_object and not target_url:
                    return "%(sender)s %(verb)s %(target)s with %(action)s" %context
                return "%(sender)s %(verb)s %(target)s" %context
            return "%(sender)s %(verb)s" %context

        @property   
        def get_link(self):
            try:
                target_url = self.target_object.get_absolute_url()
            except:
                target_url = reverse("notifications_all")

            context = {
                "sender": self.sender_object,
                "verb": self.verb,
                "action": self.action_object,
                "target": self.target_object,
                "verify_read": reverse("notifications_read", kwargs={"id": self.id}),
                "target_url": target_url,
            }
            if self.target_object:
                return "<a href='%(verify_read)s?next=%(target_url)s'>%(sender)s %(verb)s %(target)s with %(action)s</a>" %context
            else:
                return "<a href='%(verify_read)s?next=%(target_url)s'>%(sender)s %(verb)s</a>" %context


    def new_notification(sender, **kwargs):
        kwargs.pop('signal', None)
        recipient = kwargs.pop("recipient")
        verb = kwargs.pop("verb")
        affected_users = kwargs.pop('affected_users')

        #super_user_qs = MyProfile.objects.get(user=Post.moderator), 
    ''' this is wrong, It;s what I tried but failed
        if super_user_qs:
             super_user_instance = super_user_qs
             new_note = Notification(
                    recipient=super_user_instance,
                    verb = verb, # smart_text
                    sender_content_type = ContentType.objects.get_for_model(sender),
                    sender_object_id = sender.id,
                    )
             for option in ("target", "action"):
                    obj = kwargs.pop(option, None)
                    if obj is not None:
                        setattr(new_note, "%s_content_type" %option, ContentType.objects.get_for_model(obj))
                        setattr(new_note, "%s_object_id" %option, obj.id)
             new_note.save()

  the below works for notifying commentor who gets reply
  '''    
        if affected_users is not None:
            for u in affected_users:
                if u == sender:
                    pass
                else:
                    new_note = Notification(
                        recipient=recipient,
                        verb = verb, # smart_text
                        sender_content_type = ContentType.objects.get_for_model(sender),
                        sender_object_id = sender.id,
                        )
                    for option in ("target", "action"):
                        try:
                            obj = kwargs[option]
                            if obj is not None:
                                setattr(new_note, "%s_content_type" %option, ContentType.objects.get_for_model(obj))
                                setattr(new_note, "%s_object_id" %option, obj.id)
                        except:
                            pass
                    new_note.save()
        else:
            new_note = Notification(
                recipient=recipient,
                verb = verb, # smart_text
                sender_content_type = ContentType.objects.get_for_model(sender),
                sender_object_id = sender.id,
                )
            for option in ("target", "action"):
                obj = kwargs.pop(option, None)
                if obj is not None:
                    setattr(new_note, "%s_content_type" %option, ContentType.objects.get_for_model(obj))
                    setattr(new_note, "%s_object_id" %option, obj.id)
            new_note.save()


    notify.connect(new_notification)

然后在models.py我有评论和发布模型。 get_affected_user是在comment views中使用的函数来通知affected_user我相信。 (我遵循一个教程。)

And then in models.py I have comment and post models. the get_affected_user is the function that's used in comment views.py to notify affected_user I believe. (I followed a tutorial.)

class Comment(models.Model):
    user = models.ForeignKey(MyProfile)
    parent = models.ForeignKey("self", null=True, blank=True)
    post = models.ForeignKey(Post, null=True, blank=True, related_name="commented_post")
    @property 
    def get_origin(self):
        return self.path

    @property
    def get_comment(self):
        return self.text

    @property
    def is_child(self):
        if self.parent is not None:
            return True
        else:
            return False

    def get_children(self):
        if self.is_child:
            return None
        else:
            return Comment.objects.filter(parent=self)

    def get_affected_users(self):
        """ 
        it needs to be a parent and have children, 
        the children, in effect, are the affected users.
        """
        comment_children = self.get_children()
        if comment_children is not None:
            users = []
            for comment in comment_children:
                if comment.user in users:
                    pass
                else:
                    users.append(comment.user)
            return users
        return None



class Post(models.Model):

    title = models.CharField(max_length = 50)
    moderator = models.ForeignKey(User)
    views = models.IntegerField(default=0)

在views.py中进行评论,上述get_affected_user用于通知注释者得到回复我想到使用相同的功能来实现我想要的,但不能。所以我刚才把get_affected_user设置为none。

In views.py for comment, the above get_affected_user is used for notifying commentor who gets reply. I thought about using the same function to achieve what I want, but couldn't. So for that I just set get_affected_user to none for now.

def comment_create_view(request):
    if request.method == "POST" and request.user.is_authenticated():
        parent_id = request.POST.get('parent_id')
        post_id = request.POST.get("post_id")
        origin_path = request.POST.get("origin_path")
        try:
            post = Post.objects.get(id=post_id)
        except:
            post = None

        parent_comment = None
        if parent_id is not None:
            try:
                parent_comment = Comment.objects.get(id=parent_id)
            except:
                parent_comment = None

            if parent_comment is not None and parent_comment.post is not None:
                post = parent_comment.post

        form = CommentForm(request.POST)
        if form.is_valid():
            comment_text = form.cleaned_data['comment']
            if parent_comment is not None:
                # parent comments exists
                new_comment = Comment.objects.create_comment(
                    user=MyProfile.objects.get(user=request.user),
                    path=parent_comment.get_origin, 
                    text=comment_text,
                    post = post,
                    parent=parent_comment
                    )
                #affected_users = parent_comment.get_affected_users()
                #print "this is"
                affected_users = parent_comment.get_affected_users()
                notify.send(
                        MyProfile.objects.get(user=request.user), 
                        action=new_comment, 
                        target=parent_comment, 
                        recipient=parent_comment.user,
                        affected_users = affected_users,
                        verb='replied to')
                messages.success(request, "Thank you for your response.", extra_tags='safe')
                return HttpResponseRedirect(parent_comment.get_absolute_url())
            else:
                new_comment = Comment.objects.create_comment(
                    user=MyProfile.objects.get(user=request.user),
                    path=origin_path, 
                    text=comment_text,
                    post = post
                    )
                notify.send(
                        MyProfile.objects.get(user=request.user), 
                        recipient = MyProfile.objects.get(user=request.user), 
                        action=new_comment, 
                        affected_users = None,
                        target = new_comment.post,
                        verb='commented on')
                messages.success(request, "Thank you for the comment.")
                return HttpResponseRedirect(new_comment.get_absolute_url())
        else:
            messages.error(request, "There was an error with your comment.")
            return HttpResponseRedirect(origin_path)

    else:
        raise Http404

编辑:我有这个问题差不多一个星期现在.....我要求我从我购买的教程的教练那里得到一些帮助,他只用短语回答(我可以告诉他不太在意)。这是他放弃的一些提示。如果我要通知超级用户
我应该将以下内容添加到models.py以通知,

I'm having this problem for almost a week now.....I asked for some help from the instructor of the tutorial I purchased, and he only answers in short sentences(I can tell he doesn't absolutely care). Here are some hints he dropped. If I were to notify superuser I should add the following to the models.py for notification,

super_user_qs = User.objects.filter(is_admin=True)
if super_user_qs.exists():
     super_user_instance = super_user_qs.first()
     new_note = Notification(
            recipient=super_user_instance,
            verb = verb, # smart_text
            sender_content_type = ContentType.objects.get_for_model(sender),
            sender_object_id = sender.id,
            )
      for option in ("target", "action"):
            obj = kwargs.pop(option, None)
            if obj is not None:
                setattr(new_note, "%s_content_type" %option, ContentType.objects.get_for_model(obj))
                setattr(new_note, "%s_object_id" %option, obj.id)
      new_note.save()

但是我告诉他,我想通知帖子创建者/主持人,因为任何一个可以使p ost。(我告诉他几次/在他和超级用户回答之前)我应该使用模型post_save信号在我正在开发的模型中创建一个新的通知。在这种情况下,我不必使用自定义通知信号。

but then I told him, I'm trying to notify post creator/moderator because any one can make post.(I told him this couple times/before he answered with the superuser one) I should use model post_save signal to create a new Notification within the model I'm working on. and I do not have to use the custom notify signal in this case.

同时,我一直在观看教程。我想也许我只需要更改收件人= MyProfile.objects.get(user = post.moderator),
到post.moderator,但是我得到无法分配:Notification.recipient必须是一个 MyProfile实例。所以我做了收件人= MyProfile.objects.get(user = post.moderator),但这通知我关于我的评论...

Meanwhile, I was watching the tutorials over and over. I thought maybe I just need to change recipient = MyProfile.objects.get(user=post.moderator), to the post.moderator but then I get Cannot assign "": "Notification.recipient" must be a "MyProfile" instance. so I did recipient = MyProfile.objects.get(user=post.moderator), but this notify to me about the comments I make...

我真的等待任何建议
谢谢你

I really await any advise thank you

推荐答案

为了通知POST所有者,应该这样发送:

For you to notify the POST owner, it should be sent this way:

recipient = new_comment.post.moderator

而不是

recipient = MyProfile.objects.get(user=request.user) 

这将通知发送给主持人。

This would send the notification to the moderator of the Post.

这篇关于当海报收到通知后,功能会通知评论者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆