Ejemplo n.º 1
0
    def render(self, **kwargs):
        parent_type = self.parent.__class__.__name__.lower()
        request = kwargs.get('request')

        comment_page = self.parent
        if hasattr(comment_page, 'original_translation') and comment_page.original_translation:
            comment_page = comment_page.original_translation

        f = None
        if self.comments_enabled and request.POST:
            extra = request._feincms_appcontent_parameters.get('page_extra_path', ())
            if len(extra) > 0 and extra[0] == u"post-comment":
                from django.contrib.comments.views.comments import post_comment
                r = post_comment(request)
                if not isinstance(r, HttpResponseRedirect):
                    f = comments.get_form()(comment_page, data=request.POST)

        if f is None:
            f = comments.get_form()(comment_page)

        return render_to_string([
            'content/comments/%s.html' % parent_type,
            'content/comments/default-site.html',
            'content/comments/default.html',
            ], RequestContext(request, { 'content': self, 'feincms_page' : self.parent, 'parent': comment_page, 'form' : f }))
Ejemplo n.º 2
0
def post(request, username, year, month, slug,
         template_name="dpress/post.html"):
    post = Post.objects.filter(slug=slug, publish__year=int(year), 
            publish__month=int(month)).filter(author__username=username)
    if not post:
        raise Http404
    if post[0].status == 1 and post[0].author != request.user:
        raise Http404
    post=post[0]
    user = request.user
    initial={}
    if user.is_authenticated():
        initial={'name': user.username, 'email': user.email}
    form = comments.get_form()(post, initial=initial)
    if request.method == "POST":
        data = request.POST.copy()
        form = comments.get_form()(post, data=data)
        if form.is_valid():
            comment = form.get_comment_object()
            comment.ip_address = request.META.get("REMOTE_ADDR", None)
            if request.user.is_authenticated():
                comment.user = request.user
            comment.save()
    return render_to_response(template_name, {
        "post": post,
        "form": form,
    }, context_instance=RequestContext(request))
Ejemplo n.º 3
0
    def render(self, **kwargs):
        parent_type = self.parent.__class__.__name__.lower()
        request = kwargs.get('request')

        comment_page = self.parent
        if hasattr(comment_page, 'original_translation') and comment_page.original_translation:
            comment_page = comment_page.original_translation

        f = None
        if self.comments_enabled and request.POST:

            # I guess the drawback is that this page can't handle any other types of posts
            # just the comments for right now, but if we just post to the current path
            # and handle it this way .. at least it works for now.

            #extra = request._feincms_appcontent_parameters.get('page_extra_path', ())
            #if len(extra) > 0 and extra[0] == u"post-comment":

            from django.contrib.comments.views.comments import post_comment
            r = post_comment(request)
            if not isinstance(r, HttpResponseRedirect):
                f = comments.get_form()(comment_page, data=request.POST)

        if f is None:
            f = comments.get_form()(comment_page)

        return render_to_string([
            'content/comments/%s.html' % parent_type,
            'content/comments/default-site.html',
            'content/comments/default.html',
            ], RequestContext(request, { 'content': self, 'feincms_page' : self.parent, 'parent': comment_page, 'form' : f }))
Ejemplo n.º 4
0
    def test_notify_followers_dupes(self):
        # first of all confirm Bob's comment otherwise it doesn't reach DB
        self.get_confirm_comment_url(self.key)
        # then put in play pull-request-15's assert...
        # https://github.com/danirus/django-comments-xtd/pull/15
        diary = Diary.objects.create(body='Lorem ipsum', allow_comments=True)
        self.assertEqual(diary.pk, self.article.pk)

        self.form = comments.get_form()(diary)
        data = {
            "name": "Charlie",
            "email": "*****@*****.**",
            "followup": True,
            "reply_to": 0,
            "level": 1,
            "order": 1,
            "comment": "Es war einmal eine kleine..."
        }
        data.update(self.form.initial)

        self.response = self.client.post(reverse("comments-post-comment"),
                                         data=data)
        self.key = str(
            re.search(r'http://.+/confirm/(?P<key>[\S]+)',
                      self.mock_mailer.call_args[0][1]).group("key"))
        # 1) confirmation for Bob (sent in `setUp()`)
        # 2) confirmation for Charlie
        self.assertEqual(self.mock_mailer.call_count, 2)
        self.get_confirm_comment_url(self.key)
        self.assertEqual(self.mock_mailer.call_count, 2)

        self.form = comments.get_form()(self.article)
        data = {
            "name": "Alice",
            "email": "*****@*****.**",
            "followup": True,
            "reply_to": 0,
            "level": 1,
            "order": 1,
            "comment": "Es war einmal iene kleine..."
        }
        data.update(self.form.initial)
        self.response = self.client.post(reverse("comments-post-comment"),
                                         data=data)
        self.assertEqual(self.mock_mailer.call_count, 3)
        self.key = re.search(r'http://.+/confirm/(?P<key>[\S]+)',
                             self.mock_mailer.call_args[0][1]).group("key")
        self.get_confirm_comment_url(self.key)
        self.assertEqual(self.mock_mailer.call_count, 4)
        self.assert_(self.mock_mailer.call_args[0][3] == ["*****@*****.**"])
        self.assert_(self.mock_mailer.call_args[0][1].find(
            "There is a new comment following up yours.") > -1)
Ejemplo n.º 5
0
    def test_job_comment(self):
        mail.outbox = []
        self.client.login(username=self.super_username,
                          password=self.super_password)

        form = comments.get_form()(self.job1)
        url = reverse('comments-post-comment')

        form_data = {
            'name': 'Reviewer',
            'email': self.superuser.email,
            'url': 'http://example.com',
            'comment': 'Lorem ispum',
            'reply_to': 0,
            'post': 'Post'
        }
        form_data.update(form.initial)

        self.assertEqual(len(mail.outbox), 0)
        response = self.client.post(url, form_data)
        self.assertEqual(response.status_code, 302)
        self.assertIn('http://testserver/comments/posted/?c=',
                      response['Location'])

        mail_sent_queue.get(block=True)
        self.assertEqual(len(mail.outbox), 1)

        self.assertEqual(mail.outbox[0].to,
                         [self.creator.email, '*****@*****.**'])

        form = comments.get_form()(self.job1)
        form_data = {
            'name': 'creator',
            'email': self.creator.email,
            'url': 'http://example.com',
            'comment': 'Lorem ispum',
            'reply_to': 0,
            'post': 'Post'
        }
        form_data.update(form.initial)
        response = self.client.post(url, form_data)
        self.assertEqual(response.status_code, 302)
        self.assertIn('http://testserver/comments/posted/?c=',
                      response['Location'])

        mail_sent_queue.get(block=True)
        self.assertEqual(len(mail.outbox), 3)
        self.assertEqual(mail.outbox[1].to,
                         [self.creator.email, '*****@*****.**'])
        self.assertEqual(mail.outbox[2].to, [self.superuser.email])
Ejemplo n.º 6
0
 def setUp(self):
     patcher = patch('django_comments_xtd.views.send_mail')
     self.mock_mailer = patcher.start()
     self.article = Article.objects.create(
         title="September",
         slug="september",
         body="What I did on September...")
     self.form = comments.get_form()(self.article)
     data = {
         "name": "Bob",
         "email": "*****@*****.**",
         "followup": True,
         "reply_to": 0,
         "level": 1,
         "order": 1,
         "comment": "Es war einmal iene kleine..."
     }
     data.update(self.form.initial)
     self.response = self.client.post(reverse("comments-post-comment"),
                                      data=data)
     self.assert_(self.mock_mailer.call_count == 1)
     self.key = str(
         re.search(r'http://.+/confirm/(?P<key>[\S]+)',
                   self.mock_mailer.call_args[0][1]).group("key"))
     self.addCleanup(patcher.stop)
Ejemplo n.º 7
0
 def get_form(self, context):
     ctype, object_pk = self.get_target_ctype_pk(context)
     if object_pk:
         return comments.get_form()(
             ctype.get_object_for_this_type(pk=object_pk))
     else:
         return None
Ejemplo n.º 8
0
 def test_no_notification_for_same_user_email(self):
     # test that a follow-up user_email don't get a notification when
     # sending another email to the thread
     self.assertEqual(self.mock_mailer.call_count, 1)
     self.get_confirm_comment_url(self.key)  #  confirm Bob's comment
     # no comment followers yet:
     self.assertEqual(self.mock_mailer.call_count, 1)
     # send Bob's 2nd comment
     self.form = comments.get_form()(self.article)
     data = {
         "name": "Alice",
         "email": "*****@*****.**",
         "followup": True,
         "reply_to": 0,
         "level": 1,
         "order": 1,
         "comment": "Bob's comment he shouldn't get notified about"
     }
     data.update(self.form.initial)
     self.response = self.client.post(reverse("comments-post-comment"),
                                      data=data)
     self.assertEqual(self.mock_mailer.call_count, 2)
     self.key = re.search(r'http://.+/confirm/(?P<key>[\S]+)',
                          self.mock_mailer.call_args[0][1]).group("key")
     self.get_confirm_comment_url(self.key)
     self.assertEqual(self.mock_mailer.call_count, 2)
Ejemplo n.º 9
0
 def setUp(self):
     super(TestCommentModeration, self).setUp()
     self.opts = CommentOptionsObject.objects.create(
         target_ct=self.publishable.content_type,
         target_id=self.publishable.pk,
         premoderated=True)
     self.form = comments.get_form()(target_object=self.publishable)
Ejemplo n.º 10
0
def threaded_comment_json(comment, viewer):
    coll = ContentType.objects.get_for_model(Collaboration)
    all = ThreadedComment.objects.filter(
        content_type=coll, object_pk=comment.content_object.pk, site__pk=settings.SITE_ID
    )
    all = fill_tree(all)
    all = annotate_tree_properties(all)

    return {
        "type": "discussion",
        "form": comments.get_form()(comment.content_object).__unicode__(),
        "editing": True,
        "can_edit": True,
        "discussion": {
            "id": comment.id,
            "max_length": COMMENT_MAX_LENGTH,
            "thread": [
                {
                    "open": obj.open if hasattr(obj, "open") else None,
                    "close": [i for i in obj.close] if hasattr(obj, "close") else None,
                    "id": obj.id,
                    "author": obj.name,
                    "author_username": obj.user.username,
                    "submit_date": pretty_date(obj.submit_date),
                    "title": obj.title,
                    "content": obj.comment,
                    "can_edit": True if obj.user == viewer else False,
                }
                for obj in all
            ],
        },
    }
Ejemplo n.º 11
0
 def setUp(self):
     patcher = patch('django_comments_xtd.views.send_mail')
     self.mock_mailer = patcher.start()
     self.article = Article.objects.create(title="October",
                                           slug="october",
                                           body="What I did on October...")
     self.form = comments.get_form()(self.article)
Ejemplo n.º 12
0
 def test_notify_comment_followers(self):
     # send a couple of comments to the article with followup=True and check
     # that when the second comment is confirmed a followup notification
     # email is sent to the user who sent the first comment
     self.assertEqual(len(mail.outbox), 1)
     self.get_confirm_comment_url(self.key)
     self.assertEqual(len(mail.outbox), 1)  # no comment followers yet
     # send 2nd comment
     self.form = comments.get_form()(self.article)
     data = {
         "name": "Alice",
         "email": "*****@*****.**",
         "followup": True,
         "reply_to": 0,
         "level": 1,
         "order": 1,
         "comment": "Es war einmal iene kleine..."
     }
     data.update(self.form.initial)
     self.response = self.client.post(reverse("comments-post-comment"),
                                      data=data)
     if mail_sent_queue.get(block=True):
         pass
     self.assertEqual(len(mail.outbox), 2)
     self.key = re.search(r'http://.+/confirm/(?P<key>[\S]+)',
                          mail.outbox[1].body).group("key")
     self.get_confirm_comment_url(self.key)
     if mail_sent_queue.get(block=True):
         pass
     self.assertEqual(len(mail.outbox), 3)
     self.assert_(mail.outbox[2].to == ["*****@*****.**"])
     self.assert_(mail.outbox[2].body.find(
         "There is a new comment following up yours.") > -1)
Ejemplo n.º 13
0
def new_comment(request, comment_id=None, *args, **kwargs):
    
    is_ajax = request.GET.get('is_ajax') and '_ajax' or ''
    
    if not comment_id:
        return CommentPostBadRequest("Missing comment id.")
        
    parent_comment = get_model().objects.get(pk=comment_id)
    
    target = parent_comment.content_object
    model = target.__class__
    
    # Construct the initial comment form
    form = get_form()(target, parent_comment=parent_comment)
        
    template_list = [
        "comments/%s_%s_new_form%s.html" % tuple(str(model._meta).split(".") + [is_ajax]),
        "comments/%s_new_form%s.html" % (model._meta.app_label, is_ajax),
        "comments/new_form%s.html" % is_ajax,
    ]
    return render_to_response(
        template_list, {
            "form" : form,
        }, 
        RequestContext(request, {})
    )
Ejemplo n.º 14
0
def reply(request, cid):
    try:
        comment = XtdComment.objects.get(pk=cid)
    except (XtdComment.DoesNotExist):
        raise Http404

    if comment.level == max_thread_level_for_content_type(comment.content_type):
        return render_to_response(
            "django_comments_xtd/max_thread_level.html", 
            {'max_level': settings.COMMENTS_XTD_MAX_THREAD_LEVEL},
            context_instance=RequestContext(request))

    form = get_form()(comment.content_object, comment=comment)
    next = request.GET.get("next", reverse("comments-xtd-sent"))

    template_arg = [
        "django_comments_xtd/%s/%s/reply.html" % (
            comment.content_type.app_label, 
            comment.content_type.model),
        "django_comments_xtd/%s/reply.html" % (
            comment.content_type.app_label,),
        "django_comments_xtd/reply.html"
    ]
    return render_to_response(template_arg, 
                              {"comment": comment, "form": form, "next": next },
                              context_instance=RequestContext(request))
Ejemplo n.º 15
0
def new_comment(request, comment_id=None, *args, **kwargs):
    
    is_ajax = request.GET.get('is_ajax') and '_ajax' or ''
    
    if not comment_id:
        return CommentPostBadRequest("Missing comment id.")
        
    parent_comment = get_model().objects.get(pk=comment_id)
    
    target = parent_comment.content_object
    model = target.__class__
    
    # Construct the initial comment form
    form = get_form()(target, parent_comment=parent_comment)
        
    template_list = [
        "comments/%s_%s_new_form%s.html" % tuple(str(model._meta).split(".") + [is_ajax]),
        "comments/%s_new_form%s.html" % (model._meta.app_label, is_ajax),
        "comments/new_form%s.html" % is_ajax,
    ]
    return render_to_response(
        template_list, {
            "form" : form,
        }, 
        RequestContext(request, {})
    )
Ejemplo n.º 16
0
def reply(request, cid):
    try:
        comment = XtdComment.objects.get(pk=cid)
    except (XtdComment.DoesNotExist):
        raise Http404

    if comment.level == max_thread_level_for_content_type(comment.content_type):
        return render_to_response(
            "django_comments_xtd/max_thread_level.html", 
            {'max_level': settings.COMMENTS_XTD_MAX_THREAD_LEVEL},
            context_instance=RequestContext(request))

    form = get_form()(comment.content_object, comment=comment)
    next = request.GET.get("next", reverse("comments-xtd-sent"))

    template_arg = [
        "django_comments_xtd/%s/%s/reply.html" % (
            comment.content_type.app_label, 
            comment.content_type.model),
        "django_comments_xtd/%s/reply.html" % (
            comment.content_type.app_label,),
        "django_comments_xtd/reply.html"
    ]
    return render_to_response(template_arg, 
                              {"comment": comment, "form": form, "next": next },
                              context_instance=RequestContext(request))
Ejemplo n.º 17
0
 def test_notify_comment_followers(self):
     # send a couple of comments to the article with followup=True and check
     # that when the second comment is confirmed a followup notification 
     # email is sent to the user who sent the first comment
     self.assertEqual(len(mail.outbox), 1)
     self.get_confirm_comment_url(self.key)
     self.assertEqual(len(mail.outbox), 1) # no comment followers yet
     # send 2nd comment
     self.form = comments.get_form()(self.article)
     data = {"name":"Alice", "email":"*****@*****.**", "followup": True, 
             "reply_to": 0, "level": 1, "order": 1,
             "comment":"Es war einmal iene kleine..." }
     data.update(self.form.initial)
     self.response = self.client.post(reverse("comments-post-comment"), 
                                     data=data)
     if mail_sent_queue.get(block=True):
         pass
     self.assertEqual(len(mail.outbox), 2)
     self.key = re.search(r'http://.+/confirm/(?P<key>[\S]+)', 
                          mail.outbox[1].body).group("key")
     self.get_confirm_comment_url(self.key)
     if mail_sent_queue.get(block=True):
         pass
     self.assertEqual(len(mail.outbox), 3)
     self.assert_(mail.outbox[2].to == ["*****@*****.**"])
     self.assert_(mail.outbox[2].body.find("There is a new comment following up yours.") > -1)
 def get_form(self, context):
     ctype, object_pk = self.get_target_ctype_pk(context)
     if object_pk:
         return comments.get_form()(ctype.get_object_for_this_type(pk=object_pk), 
                                    parent_comment=None)
     else:
         return None
Ejemplo n.º 19
0
def new_comment(request, parent_pk=None, content_type=None, object_pk=None, *args, **kwargs):
    """
    Display the form used to post a reply. 
    
    Expects a comment_id, and an optionnal 'is_ajax' parameter in request.GET.
    """
    
    is_ajax = request.GET.get('is_ajax') and '_ajax' or ''
    data = {
        'parent_pk': parent_pk,    
        'content_type': content_type,
        'object_pk': object_pk,
    }
    response = _lookup_content_object(data)
    if isinstance(response, HttpResponse):
        return response
    else:
        target, parent_comment, model = response
    
    # Construct the initial comment form
    form = get_form()(target, parent_comment=parent_comment)
        
    template_list = [
        "comments/%s_%s_new_form%s.html" % tuple(str(model._meta).split(".") + [is_ajax]),
        "comments/%s_new_form%s.html" % (model._meta.app_label, is_ajax),
        "comments/new_form%s.html" % is_ajax,
    ]
    return TemplateResponse(request, template_list, { "form" : form })
Ejemplo n.º 20
0
def threaded_comment_json(comment, viewer):
    coll = ContentType.objects.get_for_model(Collaboration)
    all = ThreadedComment.objects.filter(content_type=coll, object_pk=comment.content_object.pk, site__pk=settings.SITE_ID)
    all = fill_tree(all)
    all = annotate_tree_properties(all)

    return {
        'type': 'discussion',
        'form': comments.get_form()(comment.content_object).__unicode__(),
        'editing': True,
        'can_edit': True,
        'discussion': {
            'id': comment.id,
            'max_length': COMMENT_MAX_LENGTH,
            'thread': [{ 'open': obj.open if hasattr(obj, "open") else None,
                         'close': [ i for i in obj.close ] if hasattr(obj, "close") else None,
                         'id': obj.id,
                         'author': obj.name,
                         'author_username': obj.user.username,
                         'submit_date': pretty_date(obj.submit_date),
                         'title': obj.title,
                         'content': obj.comment,
                         'can_edit': True if obj.user == viewer else False
                       } for obj in all]
         }
    }
Ejemplo n.º 21
0
def post(request, template_name='comments/comments.html'):
    """
    Post a comment.
    
    HTTP POST is required.
    """
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    
    try:
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.get(pk=object_pk)
    except:
        raise
    
    # Construct the comment form
    form = comments.get_form()(target, data=data)
    if not form.is_valid():
        return direct_to_template(request, template_name, {
            'object': target,
            'form': form,
        })
    
    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user
    
    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )
    
    # Save the comment and signal that it was saved
    comment.is_removed = False
    comment.save()
    signals.comment_was_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )
    
    return direct_to_template(request, template_name, {
        'object': target,
        'form': form,
    })
Ejemplo n.º 22
0
    def add(self):
        import time
        from django.db import models
        from django.contrib import comments
        from django.contrib.comments.views.comments import CommentPostBadRequest
        from django.contrib.comments import signals

        comment_form = comments.get_form()

        try:
            model = models.get_model(*self.content_type.split('.', 1))
            targets = model._default_manager.filter(pk__in = self.object_pks)
        except:
            raise

        for target in targets:
            d_form = comment_form(target)
            timestamp = str(time.time()).split('.')[0]
            object_pk = str(target.pk)
            data = {
                'content_type': self.content_type,
                'object_pk': object_pk,
                'timestamp': timestamp,
                'comment': self.comment
            }
            security_hash_dict = {
                'content_type': self.content_type,
                'object_pk': object_pk,
                'timestamp': timestamp
            }
            data['security_hash'] = d_form.generate_security_hash(**security_hash_dict)
            form = comment_form(target, data=data)

            # Response the errors if got
            if not form.is_valid():
                return form.errors

            # Otherwise create the comment
            comment = form.get_comment_object()
            comment.ip_address = self.request.META.get("REMOTE_ADDR", None)
            if self.request.user.is_authenticated():
                comment.user = self.request.user

            # Signal that the comment is about to be saved
            responses = signals.comment_will_be_posted.send(
                sender  = comment.__class__,
                comment = comment,
                request = self.request
            )

            # Save the comment and signal that it was saved
            comment.save()
            signals.comment_was_posted.send(
                sender  = comment.__class__,
                comment = comment,
                request = self.request
            )

        return
Ejemplo n.º 23
0
def threaded_comment_json(request, comment):
    viewer = request.user
    coll = ContentType.objects.get_for_model(Collaboration)
    all_comments = ThreadedComment.objects.filter(
        content_type=coll,
        object_pk=comment.content_object.pk,
        site__pk=settings.SITE_ID)
    all_comments = fill_tree(all_comments)
    all_comments = list(annotate_tree_properties(all_comments))

    rand = ''.join([choice(letters) for i in range(5)])
    citations = threaded_comment_citations(all_comments, viewer)

    asset_resource = AssetResource()
    sherd_resource = SherdNoteResource()

    return {
        'type':
        'discussion',
        'form':
        comments.get_form()(comment.content_object).__unicode__(),
        'editing':
        True,
        'can_edit':
        True,
        'discussion': {
            'id':
            comment.id,
            'max_length':
            COMMENT_MAX_LENGTH,
            'thread': [{
                'open':
                obj.open if hasattr(obj, "open") else None,
                'close':
                [i for i in obj.close] if hasattr(obj, "close") else None,
                'id':
                obj.id,
                'author':
                obj.name,
                'author_username':
                obj.user.username,
                'submit_date':
                pretty_date(obj.submit_date),
                'title':
                obj.title,
                'content':
                obj.comment,
                'can_edit':
                True if obj.user == viewer else False
            } for obj in all_comments]
        },
        'assets':
        dict([('%s_%s' % (rand, ann.asset.pk),
               asset_resource.render_one(request, ann.asset))
              for ann in citations if (ann.title != "Annotation Deleted"
                                       and ann.title != 'Asset Deleted')]),
        'annotations':
        [sherd_resource.render_one(request, ann, rand) for ann in citations],
    }
Ejemplo n.º 24
0
 def test_post_works_for_correct_data_with_parent(self):
     c = create_comment(self.publishable, self.publishable.content_type)
     form = comments.get_form()(target_object=self.publishable, parent=c.pk)
     response = self.client.post(self.get_url('new'), self.get_form_data(form))
     self.assert_equals(302, response.status_code)
     self.assert_equals(2, comments.get_model().objects.count())
     child = comments.get_model().objects.exclude(pk=c.pk)[0]
     self.assert_equals(c, child.parent)
Ejemplo n.º 25
0
 def test_post_from_banned_ip_does_not_work(self):
     template_loader.templates['page/comment_form.html'] = ''
     form = comments.get_form()(target_object=self.publishable)
     response = self.client.post(self.get_url('new'), self.get_form_data(form))
     self.assert_equals(200, response.status_code)
     self.assert_equals(0, comments.get_model().objects.count())
     self.assert_true('ip_ban' in response.context)
     self.assert_equals(self.ip_ban, response.context['ip_ban'])
Ejemplo n.º 26
0
    def test_job_comment(self):
        mail.outbox = []
        self.client.login(username=self.super_username, password=self.super_password)

        form = comments.get_form()(self.job1)
        url = reverse('comments-post-comment')

        form_data = {
            'name': 'Reviewer',
            'email': self.superuser.email,
            'url': 'http://example.com',
            'comment': 'Lorem ispum',
            'reply_to': 0,
            'post': 'Post'
        }
        form_data.update(form.initial)

        self.assertEqual(len(mail.outbox), 0)
        response = self.client.post(url, form_data)
        self.assertEqual(response.status_code, 302)
        self.assertIn('http://testserver/comments/posted/?c=', response['Location'])

        mail_sent_queue.get(block=True)
        self.assertEqual(len(mail.outbox), 1)

        self.assertEqual(mail.outbox[0].to, [self.creator.email, '*****@*****.**'])

        form = comments.get_form()(self.job1)
        form_data = {
            'name': 'creator',
            'email': self.creator.email,
            'url': 'http://example.com',
            'comment': 'Lorem ispum',
            'reply_to': 0,
            'post': 'Post'
        }
        form_data.update(form.initial)
        response = self.client.post(url, form_data)
        self.assertEqual(response.status_code, 302)
        self.assertIn('http://testserver/comments/posted/?c=', response['Location'])

        mail_sent_queue.get(block=True)
        self.assertEqual(len(mail.outbox), 3)
        self.assertEqual(mail.outbox[1].to, [self.creator.email, '*****@*****.**'])
        self.assertEqual(mail.outbox[2].to, [self.superuser.email])
 def get_form(self, context):
     ctype, object_pk = self.get_target_ctype_pk(context)
     parent_id = None
     if self.parent:
         parent_id = self.parent.resolve(context, ignore_failures=True)
     if object_pk:
         return comments.get_form()(ctype.get_object_for_this_type(pk=object_pk), parent=parent_id)
     else:
         return None
Ejemplo n.º 28
0
def post_comment(request, next=None, using=None):
    """
    Post a comment.

    HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
    errors a preview template, ``comments/preview.html``, will be rendered.
    """
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Check to see if the POST data overrides the view's next argument.
    next = data.get("next", next)

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    model = models.get_model(*ctype.split(".", 1))
    target = model._default_manager.using(using).get(pk=object_pk)


    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return None
    # Create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )

    # Save the comment and signal that it was saved
    comment.save()
    message = get_object_or_404(Message, pk = object_pk)
    message.envoyer_commentaire_notification(comment.pk, request.user.username)
    
    signals.comment_was_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )

    comment_list = [comment]
    return render_to_response('comments/list.html', {'comment_list': comment_list},context_instance=RequestContext(request))
Ejemplo n.º 29
0
 def test_post_works_for_correct_data_with_parent(self):
     c = create_comment(self.publishable, self.publishable.content_type)
     form = comments.get_form()(target_object=self.publishable, parent=c.pk)
     response = self.client.post(self.get_url('new'),
                                 self.get_form_data(form))
     self.assert_equals(302, response.status_code)
     self.assert_equals(2, comments.get_model().objects.count())
     child = comments.get_model().objects.exclude(pk=c.pk)[0]
     self.assert_equals(c, child.parent)
Ejemplo n.º 30
0
 def test_post_from_banned_ip_does_not_work(self):
     template_loader.templates['page/comment_form.html'] = ''
     form = comments.get_form()(target_object=self.publishable)
     response = self.client.post(self.get_url('new'),
                                 self.get_form_data(form))
     self.assert_equals(200, response.status_code)
     self.assert_equals(0, comments.get_model().objects.count())
     self.assert_true('ip_ban' in response.context)
     self.assert_equals(self.ip_ban, response.context['ip_ban'])
Ejemplo n.º 31
0
    def add(self):
        import time
        from django.contrib import comments
        from django.contrib.comments import signals
        from django.db import models

        comment_form = comments.get_form()

        try:
            model = models.get_model(*self.content_type.split('.', 1))
            targets = model._default_manager.filter(pk__in=self.object_pks)
        except:
            raise

        for target in targets.iterator():
            d_form = comment_form(target)
            timestamp = str(time.time()).split('.')[0]
            object_pk = str(target.pk)
            data = {
                'content_type': self.content_type,
                'object_pk': object_pk,
                'timestamp': timestamp,
                'comment': self.comment
            }
            security_hash_dict = {
                'content_type': self.content_type,
                'object_pk': object_pk,
                'timestamp': timestamp
            }
            data['security_hash'] = d_form.generate_security_hash(
                **security_hash_dict)
            form = comment_form(target, data=data)

            # Response the errors if got
            if not form.is_valid():
                return form.errors

            # Otherwise create the comment
            comment = form.get_comment_object()
            comment.ip_address = self.request.META.get("REMOTE_ADDR", None)
            if self.request.user.is_authenticated():
                comment.user = self.request.user

            # Signal that the comment is about to be saved
            responses = signals.comment_will_be_posted.send(
                sender=comment.__class__,
                comment=comment,
                request=self.request)

            # Save the comment and signal that it was saved
            comment.save()
            signals.comment_was_posted.send(sender=comment.__class__,
                                            comment=comment,
                                            request=self.request)

        return
Ejemplo n.º 32
0
    def process(self, request, **kwargs):
        parent_type = self.parent.__class__.__name__.lower()

        comment_page = self.parent
        if (hasattr(comment_page, 'original_translation')
                and comment_page.original_translation):
            comment_page = comment_page.original_translation

        f = None
        if self.comments_enabled and request.POST:

            # I guess the drawback is that this page can't handle any other
            # types of posts just the comments for right now, but if we just
            # post to the current path and handle it this way .. at least it
            # works for now.

            # extra = request._feincms_extra_context.get('page_extra_path', ())
            # if len(extra) > 0 and extra[0] == "post-comment":

            r = post_comment(request, next=comment_page.get_absolute_url())

            if isinstance(r, HttpResponseRedirect):
                return r

            f = comments.get_form()(comment_page, data=request.POST)

        if f is None:
            f = comments.get_form()(comment_page)

        self.rendered_output = render_to_string(
            [
                'content/comments/%s.html' % parent_type,
                'content/comments/default-site.html',
                'content/comments/default.html',
            ],
            RequestContext(
                request, {
                    'content': self,
                    'feincms_page': self.parent,
                    'parent': comment_page,
                    'form': f,
                }),
        )
Ejemplo n.º 33
0
    def get_form(self, context):
        parent_id = None
        if self.parent:
            parent_id = self.parent.resolve(context, ignore_failures=True)

        obj = self.get_object(context)
        if obj:
            return comments.get_form()(obj, parent=parent_id)
        else:
            return None
    def get_form(self, context):
        parent_id = None
        if self.parent:
            parent_id = self.parent.resolve(context, ignore_failures=True)

        obj = self.get_object(context)
        if obj:
            return comments.get_form()(obj, parent=parent_id)
        else:
            return None
Ejemplo n.º 35
0
 def get_form(self, context):
     ctype, object_pk = self.get_target_ctype_pk(context)
     parent_id = None
     if self.parent:
         parent_id = self.parent.resolve(context, ignore_failures=True)
     if object_pk:
         return comments.get_form()(
             ctype.get_object_for_this_type(pk=object_pk), parent=parent_id)
     else:
         return None
Ejemplo n.º 36
0
def get_comment_form(request, next=None, using=None, object_pk=None, ctype=None, curcomment=None, templates=None):
    """Request the comment by a get request
    This also assure that refreshing the error page or the detailcomment
    won't let to an http 405 error
    """
    # this is a request.GET call
    ctype = request.GET.get("ctype")
    object_pk = request.GET.get("object_pk")

    if  (ctype is None or object_pk is None) and curcomment is None:
        return CommentPostBadRequest("Missing content_type, object_pk or comment_id field.")

    # we got the ctype and object_pk but not comment_id
    if curcomment is None:
        try:
            model = models.get_model(*ctype.split(".", 1))
            target = model._default_manager.using(using).get(pk=object_pk)
        except TypeError:
            return CommentPostBadRequest(
                "Invalid content_type value: %r" % escape(ctype))
        except AttributeError:
            return CommentPostBadRequest(
                "The given content-type %r does not resolve to a valid model." % \
                    escape(ctype))
        except ObjectDoesNotExist:
            return CommentPostBadRequest(
                "No object matching content-type %r and object PK %r exists." % \
                    (escape(ctype), escape(object_pk)))
        except (ValueError, ValidationError) as e:
            return CommentPostBadRequest(
                "Attempting go get content-type %r and object PK %r exists raised %s" % \
                    (escape(ctype), escape(object_pk), e.__class__.__name__))

    else :
        if curcomment.is_removed or curcomment.is_moderated:
            # do not display reply form in those two cases
            raise Http404
        target =  curcomment.content_object

    # we are sending a new clean comment form
    form = django_comment.get_form()(target)
    ctx = {
        "form": form,
        "comment" : curcomment,
        "post": target,
        "object_pk": object_pk,
        "ctype": ctype,
        "next": get_model_target(object_pk) if curcomment is None else None,
    }

    return render_to_response(
            templates,
            ctx,
            RequestContext(request, {})
        )
Ejemplo n.º 37
0
    def setUp(self):
        # Creates an article and send two comments to the article with follow-up
        # notifications. First comment doesn't have to send any notification.
        # Second comment has to send one notification (to Bob).
        patcher = patch('django_comments_xtd.views.send_mail')
        self.mock_mailer = patcher.start()
        self.article = Article.objects.create(title="September",
                                              slug="september",
                                              body="John's September")
        self.form = comments.get_form()(self.article)

        # Bob sends 1st comment to the article with follow-up
        data = {
            "name": "Bob",
            "email": "*****@*****.**",
            "followup": True,
            "reply_to": 0,
            "level": 1,
            "order": 1,
            "comment": "Nice September you had..."
        }
        data.update(self.form.initial)
        response = self.client.post(reverse("comments-post-comment"),
                                    data=data)
        self.assert_(self.mock_mailer.call_count == 1)
        bobkey = str(
            re.search(r'http://.+/confirm/(?P<key>[\S]+)',
                      self.mock_mailer.call_args[0][1]).group("key"))
        self.get_confirm_comment_url(bobkey)  #  confirm Bob's comment

        # Alice sends 2nd comment to the article with follow-up
        data = {
            "name": "Alice",
            "email": "*****@*****.**",
            "followup": True,
            "reply_to": 1,
            "level": 1,
            "order": 1,
            "comment": "Yeah, great photos"
        }
        data.update(self.form.initial)
        response = self.client.post(reverse("comments-post-comment"),
                                    data=data)
        self.assert_(self.mock_mailer.call_count == 2)
        alicekey = str(
            re.search(r'http://.+/confirm/(?P<key>[\S]+)',
                      self.mock_mailer.call_args[0][1]).group("key"))
        self.get_confirm_comment_url(alicekey)  #  confirm Alice's comment

        # Bob receives a follow-up notification
        self.assert_(self.mock_mailer.call_count == 3)
        self.bobs_mutekey = str(
            re.search(r'http://.+/mute/(?P<key>[\S]+)',
                      self.mock_mailer.call_args[0][1]).group("key"))
        self.addCleanup(patcher.stop)
Ejemplo n.º 38
0
    def process(self, request, **kwargs):
        parent_type = self.parent.__class__.__name__.lower()

        comment_page = self.parent
        if (hasattr(comment_page, 'original_translation')
                and comment_page.original_translation):
            comment_page = comment_page.original_translation

        f = None
        if self.comments_enabled and request.POST:

            # I guess the drawback is that this page can't handle any other
            # types of posts just the comments for right now, but if we just
            # post to the current path and handle it this way .. at least it
            # works for now.

            #extra = request._feincms_extra_context.get('page_extra_path', ())
            #if len(extra) > 0 and extra[0] == "post-comment":

            r = post_comment(request, next=comment_page.get_absolute_url())

            if isinstance(r, HttpResponseRedirect):
                return r

            f = comments.get_form()(comment_page, data=request.POST)

        if f is None:
            f = comments.get_form()(comment_page)

        self.rendered_output = render_to_string(
            [
                'content/comments/%s.html' % parent_type,
                'content/comments/default-site.html',
                'content/comments/default.html',
            ],
            RequestContext(request, {
                'content': self,
                'feincms_page': self.parent,
                'parent': comment_page,
                'form': f,
            }),
        )
Ejemplo n.º 39
0
def render_review_form(request, target):
    form = comments.get_form()(target)
    context = {
        "comment" : form.data.get("comment", ""),
        "form" : form,
        "item": target,
    }
    request_context = RequestContext(request, {})
    return render_to_string(get_template_list(Item, 'form'), 
                            context, 
                            request_context)
Ejemplo n.º 40
0
    def test_notify_followers_dupes(self):
        # first of all confirm Bob's comment otherwise it doesn't reach DB
        self.get_confirm_comment_url(self.key)
        # then put in play pull-request-15's assert...
        # https://github.com/danirus/django-comments-xtd/pull/15
        diary = Diary.objects.create(
            body='Lorem ipsum',
            allow_comments=True
        )
        self.assertEqual(diary.pk, self.article.pk)

        self.form = comments.get_form()(diary)
        data = {"name": "Charlie", "email": "*****@*****.**", 
                "followup": True, "reply_to": 0, "level": 1, "order": 1,
                "comment": "Es war einmal eine kleine..." }
        data.update(self.form.initial)

        self.response = self.client.post(reverse("comments-post-comment"), 
                                        data=data)
        self.key = str(re.search(r'http://.+/confirm/(?P<key>[\S]+)', 
                                 self.mock_mailer.call_args[0][1]).group("key"))
        # 1) confirmation for Bob (sent in `setUp()`)
        # 2) confirmation for Charlie
        self.assertEqual(self.mock_mailer.call_count, 2)
        self.get_confirm_comment_url(self.key)
        self.assertEqual(self.mock_mailer.call_count, 2)

        self.form = comments.get_form()(self.article)
        data = {"name":"Alice", "email":"*****@*****.**", "followup": True, 
                "reply_to": 0, "level": 1, "order": 1,
                "comment":"Es war einmal iene kleine..." }
        data.update(self.form.initial)
        self.response = self.client.post(reverse("comments-post-comment"), 
                                        data=data)
        self.assertEqual(self.mock_mailer.call_count, 3)
        self.key = re.search(r'http://.+/confirm/(?P<key>[\S]+)', 
                             self.mock_mailer.call_args[0][1]).group("key")
        self.get_confirm_comment_url(self.key)
        self.assertEqual(self.mock_mailer.call_count, 4)
        self.assert_(self.mock_mailer.call_args[0][3] == ["*****@*****.**"])
        self.assert_(self.mock_mailer.call_args[0][1].find("There is a new comment following up yours.") > -1)
Ejemplo n.º 41
0
 def get_form(self, context):
     ctype, object_pk = self.get_target_ctype_pk(context)
     if object_pk:
         initial = None
         if 'user' in context and context['user'].is_authenticated():
             initial = { 'name': (context['user'].get_full_name() or 
                                  context['user'].username),
                         'email': context['user'].email }
         return comments.get_form()(
             ctype.get_object_for_this_type(pk=object_pk), initial=initial)
     else:
         return None
Ejemplo n.º 42
0
def comment(request) :
    if request.method == 'POST' :
        prod_id = request.POST['object_pk']
        prod = Product.objects.get(pk=prod_id)
        post_values = request.POST.copy()
        post_values['name']= request.user.first_name + request.user.last_name
        post_values['email']= request.user.email
        comm_form = get_form()
        form = comm_form(target_object=prod, data=post_values)
        if (form.is_valid()) :
            form.save()  
        return HttpResponseRedirect(request.POST['next'])
    return HttpResponseRedirect('/')
Ejemplo n.º 43
0
def comment(request):
    if request.method == 'POST':
        prod_id = request.POST['object_pk']
        prod = Product.objects.get(pk=prod_id)
        post_values = request.POST.copy()
        post_values['name'] = request.user.first_name + request.user.last_name
        post_values['email'] = request.user.email
        comm_form = get_form()
        form = comm_form(target_object=prod, data=post_values)
        if (form.is_valid()):
            form.save()
        return HttpResponseRedirect(request.POST['next'])
    return HttpResponseRedirect('/')
Ejemplo n.º 44
0
 def _post_comment(self, data=None, parent=None):
     Comment = comments.get_model()
     body = (data or self.BASE_DATA).copy()
     url = comments.get_form_target()
     args = [Site.objects.all()[0]]
     kwargs = {}
     if parent is not None:
         kwargs['parent'] = unicode(parent.pk)
         body['parent'] = unicode(parent.pk)
     form = comments.get_form()(*args, **kwargs)
     body.update(form.generate_security_data())
     self.client.post(url, body, follow=True)
     return Comment.objects.order_by('-id')[0]
Ejemplo n.º 45
0
def __get_form(request):
    """
    Validates and returns the form. Modified post_comment from 
    django.contrib.comments.views.comments
    """
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name(
            ) or request.user.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Check to see if the POST data overrides the view's next argument.
    #next = data.get("next", next) #not necessary

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest(
            "Missing content_type or object_pk field.")
    try:
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.get(pk=object_pk)
    except TypeError:
        return CommentPostBadRequest("Invalid content_type value: %r" %
                                     escape(ctype))
    except AttributeError:
        return CommentPostBadRequest(
            "The given content-type %r does not resolve to a valid model." % \
                escape(ctype))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
                (escape(ctype), escape(object_pk)))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: %s" % \
                escape(str(form.security_errors())))

    return form
Ejemplo n.º 46
0
def restaurant(request, slug):
    restaurant = get_object_or_404(Restaurant, slug=slug)
    mform = MenuItemForm(prefix="menu")
    cform = comments.get_form()(restaurant)
    ajax = process_ajax(request, restaurant)
    if ajax:
        return ajax
    if request.method == "POST":
        if request.GET["type"] == "menu":
            mform = MenuItemForm(request.POST, prefix="menu")
            if mform.is_valid():
                model = mform.save(commit=False)
                model.user = request.user
                model.restaurant = restaurant
                model.is_available = True
                model.save()
                mform = MenuItemForm(prefix="menu")
                return HttpResponseRedirect("./")
        else :
            cform = comments.get_form()(restaurant, data=request.POST.copy())
            if cform.is_valid():
                comment = cform.get_comment_object()
                comment.ip_address = request.META.get("REMOTE_ADDR", None)
                if request.user.is_authenticated():
                    comment.user = request.user
                comment.save()
                cform = comments.get_form()(restaurant)
                return HttpResponseRedirect("./")
    del cform.fields['honeypot']
    del cform.fields['url']  
    referer = request.environ.get("HTTP_REFERER")
    if referer != None:
        if  referer.startswith("http://stumptownvegans.com/") or referer.startswith("http://localhost:8000/") and not ReferingSite.objects.all().filter(url=referer) and not ReferingSite.objects.all().filter(restaurant=restaurant):
            try:
                ReferingSite(restaurant=restaurant, url=referer).save()
            except:
                logging.critical(traceback.format_exc())
    return render_to_response("restaurants/restaurant_detail.html", {'menu_form': mform, 'comment_form': cform, 'object': restaurant, 'menu':restaurant.menuitem_set.all().order_by("category") ,'tags':getTags(restaurant)}, context_instance=RequestContext(request))
Ejemplo n.º 47
0
 def post_comment_as_logged_in_user(self):
     c = create_comment(self.publishable, self.publishable.content_type)
     boy = User.objects.create(username='******', email='*****@*****.**')
     boy.set_password('boy')
     boy.save()
     self.client.login(username='******', password='******')
     form = comments.get_form()(target_object=self.publishable, parent=c.pk)
     data = { 'name': '', 'email': '', }
     response = self.client.post(self.get_url('new'), self.get_form_data(form, **data))
     tools.assert_equals(302, response.status_code)
     tools.assert_equals(2, comments.get_model().objects.count())
     child = comments.get_model().objects.exclude(pk=c.pk)[0]
     tools.assert_equals(u'boy', child.user_name)
     tools.assert_equals(u'*****@*****.**', child.user_email)
Ejemplo n.º 48
0
    def setUp(self):
        # Create an article and send a comment. Test method will chech headers
        # to see wheter messages has multiparts or not.
        patcher = patch('django_comments_xtd.views.send_mail')
        self.mock_mailer = patcher.start()
        self.article = Article.objects.create(
            title="September", slug="september", body="John's September")
        self.form = comments.get_form()(self.article)

        # Bob sends 1st comment to the article with follow-up
        self.data = {"name": "Bob", "email": "*****@*****.**", 
                     "followup": True, "reply_to": 0, "level": 1, "order": 1,
                     "comment": "Nice September you had..." }
        self.data.update(self.form.initial)
Ejemplo n.º 49
0
 def setUp(self):
     self.article = Article.objects.create(title="September", 
                                           slug="september",
                                           body="What I did on September...")
     self.form = comments.get_form()(self.article)
     data = {"name":"Bob", "email":"*****@*****.**", "followup": True, 
             "comment":"Es war einmal iene kleine..." }
     data.update(self.form.initial)
     self.response = self.client.post(reverse("comments-post-comment"), 
                                     data=data)
     if mail_sent_queue.get(block=True):
         pass
     self.key = re.search(r'http://.+/confirm/(?P<key>[\S]+)', 
                          mail.outbox[0].body).group("key")
Ejemplo n.º 50
0
    def process(self, request, **kwargs):
        parent_type = self.parent.__class__.__name__.lower()

        comment_page = self.parent
        if hasattr(comment_page, "original_translation") and comment_page.original_translation:
            comment_page = comment_page.original_translation

        f = None
        if self.comments_enabled and request.POST:

            # I guess the drawback is that this page can't handle any other types of posts
            # just the comments for right now, but if we just post to the current path
            # and handle it this way .. at least it works for now.

            # extra = request._feincms_extra_context.get('page_extra_path', ())
            # if len(extra) > 0 and extra[0] == u"post-comment":

            from django.contrib.comments.views.comments import post_comment

            r = post_comment(request, next=comment_page.get_absolute_url())

            if isinstance(r, HttpResponseRedirect):
                return r

            f = comments.get_form()(comment_page, data=request.POST)

        if f is None:
            f = comments.get_form()(comment_page)

        self.rendered_output = render_to_string(
            [
                "content/comments/%s.html" % parent_type,
                "content/comments/default-site.html",
                "content/comments/default.html",
            ],
            RequestContext(request, {"content": self, "feincms_page": self.parent, "parent": comment_page, "form": f}),
        )
Ejemplo n.º 51
0
def reply(request, comment_id, template_name="comments/reply_form.html"):
    comment = get_object_or_404(comments.get_model(), pk=comment_id)
    form = comments.get_form()(comment.content_object,
                               initial={
                                   "parent_id": comment.id
                               })

    return render(
        request, template_name, {
            "object": comment.content_object,
            "form": form,
            "form_id": "{}-reply-{}".format(comment.content_object.id,
                                            comment_id),
            "form_target": reverse("comment_reply", args=[comment_id]),
        })
Ejemplo n.º 52
0
 def _post_comment(self, data=None, parent=None):
     Comment = comments.get_model()
     body = self.BASE_DATA.copy()
     if data:
         body.update(data)
     url = comments.get_form_target()
     args = [Site.objects.all()[0]]
     kwargs = {}
     if parent is not None:
         kwargs['parent'] = unicode(parent.pk)
         body['parent'] = unicode(parent.pk)
     form = comments.get_form()(*args, **kwargs)
     body.update(form.generate_security_data())
     self.client.post(url, body, follow=True)
     return Comment.objects.order_by('-id')[0]
Ejemplo n.º 53
0
 def get_form(self, context):
     ctype, object_pk = self.get_target_ctype_pk(context)
     if object_pk:
         initial = None
         if 'user' in context and context['user'].is_authenticated():
             initial = {
                 'name': (context['user'].get_full_name()
                          or context['user'].username),
                 'email':
                 context['user'].email
             }
         return comments.get_form()(
             ctype.get_object_for_this_type(pk=object_pk), initial=initial)
     else:
         return None
Ejemplo n.º 54
0
def create(request,
           content_type_id,
           object_id,
           template_name="comments/reply_form.html"):
    print content_type_id, object_id
    ctype = get_object_or_404(ContentType, id=content_type_id)
    entity = get_object_or_404(ctype.model_class(), pk=object_id)
    print ctype, entity
    form = comments.get_form()(entity)
    return render(
        request, template_name, {
            "object": entity,
            "form": form,
            "form_id": "{}-comment".format(entity.id),
        })
Ejemplo n.º 55
0
Archivo: views.py Proyecto: ng/tbonline
def post_comment(request, next=None, using=None):
    form = RecaptchaForm(request.POST)
    data = request.session['data']
    model = request.session['model']
    target = request.session['target']
    next = data.get("next", next)
    if form.is_valid():
        form = comments.get_form()(target, data=data)
        comment = form.get_comment_object()
        comment.ip_address = request.META.get("REMOTE_ADDR", None)
        if request.user.is_authenticated():
            comment.user = request.user

        # Signal that the comment is about to be saved
        responses = signals.comment_will_be_posted.send(
            sender=comment.__class__, comment=comment, request=request)

        for (receiver, response) in responses:
            if response == False:
                return CommentPostBadRequest(
                    "comment_will_be_posted receiver %r killed the comment" %
                    receiver.__name__)

        # Save the comment and signal that it was saved
        comment.save()
        signals.comment_was_posted.send(sender=comment.__class__,
                                        comment=comment,
                                        request=request)
        return next_redirect(data, next, comment_done, c=comment._get_pk_val())
    else:
        template_list = [
            "comments/%s_%s_verify.html" %
            (model._meta.app_label, model._meta.module_name),
            "comments/%s_verify.html" % model._meta.app_label,
            "comments/%s/%s/verify.html" %
            (model._meta.app_label, model._meta.module_name),
            "comments/%s/verify.html" % model._meta.app_label,
            "comments/verify.html",
        ]
        return render_to_response(
            template_list, {
                "comment": request.session['data'].get("comment", ""),
                "form": form,
                "next": next,
            }, RequestContext(request, {}))
Ejemplo n.º 56
0
    def test_get_comment_create_data(self):
        # as it's used in django.contrib.comments.views.comments
        data = {"name":"Daniel", 
                "email":"*****@*****.**", 
                "followup": True, 
                "comment":"Es war einmal iene kleine..." }
        data.update(self.form.initial)
        form = comments.get_form()(self.article, data)
        self.assert_(self.form.security_errors() == {})
        self.assert_(self.form.errors == {})
        comment = form.get_comment_object()

        # it does have the new field 'followup'
        self.assert_(comment.has_key("followup"))

        # and as long as settings.COMMENTS_XTD_CONFIRM_EMAIL is True
        # is_public is set to False until receive the user confirmation
        self.assert_(comment.is_public == False) 
Ejemplo n.º 57
0
def lucidTag(request):
    if (settings.DEBUG or request.user.is_superuser) and not settings.ADMINS:
        messages.info(request, "Please fill out settings.ADMINS!")

    object2comment = request.PYLUCID.object2comment

    if object2comment == False:
        # Don't display pylucid comments on this page
        # e.g. search get view display search results
        return ""

    form = comments.get_form()(object2comment)
    context = {
        "form":form,
        "object2comment": object2comment,
    }
    return render_to_response("pylucid_comments/comments.html",
        context, context_instance=RequestContext(request)
    )
Ejemplo n.º 58
0
def post_comment(request, next=None, using=None):
    if request.is_ajax():

        # Fill out some initial data fields from an authenticated user, if present
        data = request.POST.copy()

        if not data.get('name', ''):
            data["name"] = request.user.username
        if not data.get('email', ''):
            data["email"] = request.user.email
        print >> sys.stderr, data

        # Look up the object we're trying to comment about
        ctype = data.get("content_type")
        object_pk = data.get("object_pk")

        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.using(using).get(pk=object_pk)
        # Construct the comment form
        form = comments.get_form()(target, data=data)

        # Otherwise create the comment
        comment = form.get_comment_object()
        comment.ip_address = request.META.get("REMOTE_ADDR", None)
        if request.user.is_authenticated():
            comment.user = request.user

        # Signal that the comment is about to be saved
        responses = signals.comment_will_be_posted.send(
            sender=comment.__class__, comment=comment, request=request)

        # Save the comment and signal that it was saved
        comment.save()

        signals.comment_was_posted.send(sender=comment.__class__,
                                        comment=comment,
                                        request=request)

        return render_to_response('recipe/comment.html', {'comment': comment})
    else:
        raise http.Http404