def get_comment_object(self): """ Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user`` or ``ip_address``). """ if not self.is_valid(): raise ValueError("get_comment_object may only be called on valid forms") parent_comment = None parent_pk = self.cleaned_data.get("parent_pk") if parent_pk: parent_comment = get_model().objects.get(pk=parent_pk) new = get_model()( content_type = ContentType.objects.get_for_model(self.target_object), object_pk = force_unicode(self.target_object._get_pk_val()), user_name = "", # self.cleaned_data["name"], user_email = "", # self.cleaned_data["email"], user_url = "", # self.cleaned_data["url"], comment = self.cleaned_data["comment"], submit_date = datetime.datetime.now(), site_id = settings.SITE_ID, is_public = parent_comment and parent_comment.is_public or True, is_removed = False, title = self.cleaned_data["title"], parent = parent_comment ) # FIXME: maybe re-implement duplicate checking later return new
def _lookup_content_object(data): # Look up the object we're trying to comment about ctype = data.get("content_type") object_pk = data.get("object_pk") parent_pk = data.get("parent_pk") if parent_pk: try: parent_comment = get_model().objects.get(pk=parent_pk) target = parent_comment.content_object model = target.__class__ except get_model().DoesNotExist: return CommentPostBadRequest( "Parent comment with PK %r does not exist." % \ escape(parent_pk)) elif ctype and object_pk: try: parent_comment = None 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))) else: return CommentPostBadRequest("Missing content_type or object_pk field.") return (target, parent_comment, model)
def connect(self): """ Hook up the moderation methods to pre- and post-save signals from the comment models. """ signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=django_comments.get_model()) signals.comment_was_posted.connect(self.post_save_moderation, sender=django_comments.get_model())
def test_post_comment_child(self): Comment = django_comments.get_model() comment = self._post_comment() self.assertEqual(comment.tree_path, str(comment.pk).zfill(PATH_DIGITS)) child_comment = self._post_comment(data={'name': 'ericflo'}, parent=comment) comment_pk = str(comment.pk).zfill(PATH_DIGITS) child_comment_pk = str(child_comment.pk).zfill(PATH_DIGITS) self.assertEqual(child_comment.tree_path, PATH_SEPARATOR.join((comment.tree_path, child_comment_pk))) self.assertEqual(comment.pk, child_comment.parent.pk) comment = django_comments.get_model().objects.get(pk=comment.pk) self.assertEqual(comment.last_child, child_comment)
def test_post_comment_child(self): Comment = django_comments.get_model() comment = self._post_comment() self.assertEqual(comment.tree_path, str(comment.pk).zfill(PATH_DIGITS)) child_comment = self._post_comment(data={'name': 'ericflo'}, parent=comment) comment_pk = str(comment.pk).zfill(PATH_DIGITS) child_comment_pk = str(child_comment.pk).zfill(PATH_DIGITS) self.assertEqual( child_comment.tree_path, PATH_SEPARATOR.join((comment.tree_path, child_comment_pk))) self.assertEqual(comment.pk, child_comment.parent.pk) comment = django_comments.get_model().objects.get(pk=comment.pk) self.assertEqual(comment.last_child, child_comment)
def test_do_email_reply(self): comment = comments.get_model().objects.create( comment='My Comment 1', user=self.author, is_public=True, content_object=self.entry, submit_date=timezone.now(), site=self.site) moderator = EntryCommentModerator(Entry) moderator.email_notification_reply = True moderator.mail_comment_notification_recipients = [ '*****@*****.**', '*****@*****.**' ] moderator.do_email_reply(comment, self.entry, 'request') self.assertEqual(len(mail.outbox), 0) comment = comments.get_model().objects.create( comment='My Comment 2', user_email='*****@*****.**', content_object=self.entry, is_public=True, submit_date=timezone.now(), site=self.site) moderator.do_email_reply(comment, self.entry, 'request') self.assertEqual(len(mail.outbox), 0) comment = comments.get_model().objects.create( comment='My Comment 3', user_email='*****@*****.**', content_object=self.entry, is_public=True, submit_date=timezone.now(), site=self.site) moderator.do_email_reply(comment, self.entry, 'request') self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].bcc, ['*****@*****.**']) comment = comments.get_model().objects.create( comment='My Comment 4', user=self.author, is_public=True, content_object=self.entry, submit_date=timezone.now(), site=self.site) moderator.do_email_reply(comment, self.entry, 'request') self.assertEqual(len(mail.outbox), 2) self.assertEqual(set(mail.outbox[1].bcc), set(['*****@*****.**', '*****@*****.**']))
def test_deletion_of_last_child_marks_parent_as_childless(self): ct = ContentType.objects.get_for_model(Site) Comment = django_comments.get_model() c = Comment.objects.get(pk=6) c.delete() c = Comment.objects.get(pk=4) self.assertEqual(None, c.last_child)
def accepted_answer(request, slug, comment): instance = get_object_or_404(sm.Question,slug=slug, site=settings.SITE_ID) Comment = django_comments.get_model() comment = get_object_or_404(Comment,pk=comment) if not instance == comment.content_object: raise Http404 if not request.user.has_perm('stack.change_question') and not request.user == instance.comment.user: raise Http404 if instance.accepted_answer: messages.warning(request,"You have changed the accepted answer") else: messages.success(request,"Answer has been marked as accepted") if request.user.has_perm('stack.change_question'): # Admin therefore adminlog LogEntry.objects.log_action( request.user.pk, ContentType.objects.get_for_model(instance).pk, instance.pk, '%s' % instance, CHANGE, "from [%s] to [%s]" % (instance.accepted_answer, comment) ) instance.accepted_answer = comment instance.has_answer = True instance.save() return redirect(instance.get_absolute_url())
def test_post_comment(self): Comment = django_comments.get_model() self.assertEqual(Comment.objects.count(), 0) comment = self._post_comment() self.assertEqual(comment.tree_path, str(comment.pk).zfill(PATH_DIGITS)) self.assertEqual(Comment.objects.count(), 1) self.assertEqual(comment.last_child, None)
def test_last_child_properly_created(self): ct = ContentType.objects.get_for_model(Site) Comment = django_comments.get_model() new_child_comment = Comment(comment="Comment 8", site_id=1, content_type=ct, object_pk=1, parent_id=1) new_child_comment.save() comment = Comment.objects.get(pk=1) self.assertEqual(comment.last_child, new_child_comment)
def flag(request, comment_id, next=None): """ Flags a comment. Confirmation on GET, action on POST. Templates: :template:`comments/flag.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(django_comments.get_model(), pk=comment_id, site__pk=get_current_site(request).pk) # Flag on POST if request.method == 'POST': perform_flag(request, comment) return next_redirect(request, fallback=next or 'comments-flag-done', c=comment.pk) # Render a form on GET else: return render(request, 'comments/flag.html', { 'comment': comment, "next": next })
def approve(request, comment_id, next=None): """ Approve a comment (that is, mark it as public and non-removed). Confirmation on GET, action on POST. Requires the "can moderate comments" permission. Templates: :template:`comments/approve.html`, Context: comment the `comments.comment` object for approval """ comment = get_object_or_404(django_comments.get_model(), pk=comment_id, site__pk=get_current_site(request).pk) # Delete on POST if request.method == 'POST': # Flag the comment as approved. perform_approve(request, comment) return next_redirect(request, fallback=next or 'comments-approve-done', c=comment.pk) # Render a form on GET else: return render(request, 'comments/approve.html', { 'comment': comment, "next": next })
def connect(self): comment_will_be_posted.connect(self.pre_save_moderation, sender=TmpXtdComment) confirmation_received.connect(self.post_save_moderation, sender=TmpXtdComment) comment_was_flagged.connect(self.comment_flagged, sender=get_model())
def approve_photo_comment(request, comment_id, next=None): """ Approve a comment on a photo (i.e., mark it as public). This view also checks the current user has ownership of the photoset that the comment belongs to. Redirects to provided next arg or to the photo's page upon approval. """ comment = get_object_or_404(django_comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) try: photo = comment.content_object photoset = photo.photoset except AttributeError: raise if request.user != photoset.owner: raise PermissionDenied perform_approve(request, comment) messages.add_message(request, messages.SUCCESS, "Comment approved.") return redirect(photo if not next else next)
def __init__(self, *args, **kwargs): super(CommentsRelation, self).__init__( to=comments.get_model(), content_type_field='content_type', object_id_field='object_pk', **kwargs )
def comments_delete(request, comment_id): """Delete comment view.""" comment = get_object_or_404(django_comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) context = { 'next': request.GET.get('next'), 'comment': comment, 'is_popup': "_popup" in request.REQUEST } if request.method == 'POST': perform_delete(request, comment) if context['is_popup']: return render_to_response( 'admin/close_popup.html', context, RequestContext(request)) else: return next_redirect( request, fallback=request.GET.get('next') or 'comments-delete-done', c=comment.pk) else: return render_to_response( 'comments/delete.html', context, RequestContext(request))
def test_pingback_extensions_get_pingbacks(self): target = "http://%s%s" % (self.site.domain, self.first_entry.get_absolute_url()) source = "http://%s%s" % (self.site.domain, self.second_entry.get_absolute_url()) response = self.server.pingback.ping(source, target) self.assertEqual(response, "Pingback from %s to %s registered." % (source, target)) response = self.server.pingback.extensions.getPingbacks("http://external/") self.assertEqual(response, 32) response = self.server.pingback.extensions.getPingbacks("http://example.com/error-404/") self.assertEqual(response, 32) response = self.server.pingback.extensions.getPingbacks("http://example.com/2010/") self.assertEqual(response, 33) response = self.server.pingback.extensions.getPingbacks(source) self.assertEqual(response, []) response = self.server.pingback.extensions.getPingbacks(target) self.assertEqual(response, ["http://example.com/2010/01/01/my-second-entry/"]) comment = comments.get_model().objects.create( content_type=ContentType.objects.get_for_model(Entry), object_pk=self.first_entry.pk, site=self.site, submit_date=timezone.now(), comment="Test pingback", user_url="http://external/blog/1/", user_name="Test pingback", ) comment.flags.create(user=self.author, flag=PINGBACK) response = self.server.pingback.extensions.getPingbacks(target) self.assertEqual(response, ["http://example.com/2010/01/01/my-second-entry/", "http://external/blog/1/"])
def send_action_mail(action): users = set(filter(lambda x: x.userprofile.notify_by_email, reduce(lambda res, x: (res | set(followers(x))) if x else res, [action.actor, action.action_object, action.target], set()))) q = None if isinstance(action.action_object, Task): q = Q(userprofile__notify_about_new_tasks=True) if isinstance(action.action_object, Service): q = Q(userprofile__notify_about_new_services=True) if q: users |= set(User.objects.filter(q & Q(userprofile__notify_by_email=True))) connection = get_connection(fail_silently=True) site = Site.objects.get(pk=1) messages = [] emails = set() if hasattr(action.actor, 'email'): emails.add(action.actor.email) for user in users: if user.email in emails: continue messages.append(create_action_email( Context({'action': action, 'user': user, 'site': site}), user.email, connection)) emails.add(user.email) if isinstance(action.action_object, django_comments.get_model()) and action.action_object.parent \ and not action.action_object.parent.user and action.action_object.parent.email not in emails: messages.append(create_action_email( Context({'action': action, 'user_name': action.action_object.parent.name, 'site': site}), action.action_object.parent.email, connection)) connection.send_messages(messages)
def on_comment_post_save(sender, **kwargs): model = django_comments.get_model() if issubclass(sender, model): obj = kwargs['instance'].content_object if isinstance(obj, jmbo.models.ModelBase): obj.comment_count = obj._comment_count obj.save(set_modified=False)
def comments_delete(request, comment_id): """Delete comment view.""" comment = get_object_or_404(django_comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) context = { 'next': request.GET.get('next'), 'comment': comment, 'is_popup': "_popup" in request.REQUEST } if request.method == 'POST': perform_delete(request, comment) if context['is_popup']: return render_to_response('admin/close_popup.html', context, RequestContext(request)) else: return next_redirect(request, fallback=request.GET.get('next') or 'comments-delete-done', c=comment.pk) else: return render_to_response('comments/delete.html', context, RequestContext(request))
def delete(request, comment_id, next=None): """ Deletes a comment. Confirmation on GET, action on POST. Requires the "can moderate comments" permission. Templates: :template:`comments/delete.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(django_comments.get_model(), pk=comment_id, site__pk=get_current_site(request).pk) # Delete on POST if request.method == 'POST': # Flag the comment as deleted instead of actually deleting it. perform_delete(request, comment) return next_redirect(request, fallback=next or 'comments-delete-done', c=comment.pk) # Render a form on GET else: return render(request, 'comments/delete.html', { 'comment': comment, "next": next })
def test_comment_success(self): with self.assertNumQueries(0): response = self.client.get('/comments/success/') self.assertTemplateUsed(response, 'comments/zinnia/entry/posted.html') self.assertEqual(response.context['comment'], None) with self.assertNumQueries(1): response = self.client.get('/comments/success/?c=404') self.assertEqual(response.context['comment'], None) comment = comments.get_model().objects.create( submit_date=timezone.now(), comment='My Comment 1', content_object=self.category, site=self.site, is_public=False) success_url = '/comments/success/?c=%s' % comment.pk with self.assertNumQueries(1): response = self.client.get(success_url) self.assertEqual(response.context['comment'], comment) comment.is_public = True comment.save() with self.assertNumQueries(5): response = self.client.get(success_url, follow=True) self.assertEqual(response.redirect_chain[1], ('http://example.com/categories/tests/', 302))
def create_comment(request, content_object, author, comment): site = get_current_site(request) comment_model = django_comments.get_model() new_comment = comment_model(content_object=content_object, user=author, comment=comment, site=site) new_comment.save() return new_comment
def create_comment(data=None, parent=None, target=None, user=None): from django.test import Client import django_comments as comments from django.contrib.sites.models import Site Comment = comments.get_model() body = { 'name': 'user_anonymous_name', 'email': '*****@*****.**', 'comment': 'test_comment', } if data: body.update(data) url = comments.get_form_target() args = [target if target else Site.objects.all()[0]] kwargs = {} if parent is not None: kwargs['parent'] = str(parent.pk) body['parent'] = str(parent.pk) form = comments.get_form()(*args, **kwargs) body.update(form.generate_security_data()) client = Client() if user: client.force_login(user) client.post(url, body, follow=True) return Comment.objects.last()
def send_comment_email(comment, src_url='http://chenzhibin.vip/'): #获得被评论的对象 content_type = comment.content_type model_object = content_type.get_object_for_this_type(id=comment.object_pk) #不注释会出错,所以,如果不是本博主发的文,他收不到评论提醒 # email_address = model_object.author.email #获取被评论对象的作者邮箱 #构造评论模版所需的数据 email_data = {} email_data['comment_name'] = comment.name email_data['comment_content'] = comment.comment email_data['comment_url'] = u'%s#F%s' % (src_url, comment.id) #其他设置 to_list = [] if int(comment.root_id) == 0: subject = u'[陈志斌的博客]有人评论' template = 'email/comment.html' # to_list.append(email_address) to_list.append(settings.DEFAULT_FROM_EMAIL) else: subject = u'[陈志斌的博客]评论回复' template = 'email/reply.html' comment_model = django_comments.get_model() cams = comment_model.objects.filter(id=comment.reply_to) if cams: to_list.append(cams[0].user_email) to_list.append(settings.DEFAULT_FROM_EMAIL) else: #没有找到评论,就发给自己 to_list.append(settings.DEFAULT_FROM_EMAIL) # 根据模版发送邮件 send_email_by_template(subject, template, email_data, to_list)
def approve(request, comment_id, next=None): """ Approve a comment (that is, mark it as public and non-removed). Confirmation on GET, action on POST. Requires the "can moderate comments" permission. Templates: :template:`comments/approve.html`, Context: comment the `comments.comment` object for approval """ comment = get_object_or_404(django_comments.get_model(), pk=comment_id) # Delete on POST if request.method == 'POST': # Flag the comment as approved. perform_approve(request, comment) return next_redirect(request, fallback=next or 'comments-approve-done', c=comment.pk) # Render a form on GET else: return render_to_response( 'comments/approve.html', {'comment': comment, "next": next}, template.RequestContext(request) )
def delete(request): """Deletes a comment""" ajax_response = {'rc': 0, 'response': 'ok'} comments_s = comments.get_model().objects.filter( pk__in=request.POST.getlist('comment_id'), site__pk=settings.SITE_ID, is_removed=False, user_id=request.user.id) if not comments_s: if request.is_ajax(): ajax_response = {'rc': 1, 'response': 'Object does not exist.'} return JsonResponse(ajax_response) raise ObjectDoesNotExist() # Flag the comment as deleted instead of actually deleting it. for comment in comments_s: if comment.user == request.user: flag, created = comments.models.CommentFlag.objects.get_or_create( comment=comment, user=request.user, flag=comments.models.CommentFlag.MODERATOR_DELETION) comment.is_removed = True comment.save() comments.signals.comment_was_flagged.send( sender=comment.__class__, comment=comment, flag=flag, created=created, request=request, ) return JsonResponse(ajax_response)
def test_do_email_authors_without_email(self): """ https://github.com/Fantomas42/django-blog-zinnia/issues/145 """ comment = comments.get_model().objects.create( comment='My Comment', user=self.author, is_public=True, content_object=self.entry, submit_date=timezone.now(), site=self.site) self.assertEqual(len(mail.outbox), 0) moderator = EntryCommentModerator(Entry) moderator.email_authors = True moderator.mail_comment_notification_recipients = [] contributor = Author.objects.create(username='******', email='*****@*****.**') self.entry.authors.add(contributor) moderator.do_email_authors(comment, self.entry, 'request') self.assertEqual(len(mail.outbox), 1) self.assertEqual(set(mail.outbox[0].to), set(['*****@*****.**', '*****@*****.**'])) mail.outbox = [] contributor.email = '' contributor.save() moderator.do_email_authors(comment, self.entry, 'request') self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
def test_do_email_authors_without_email(self): """ https://github.com/Fantomas42/django-blog-zinnia/issues/145 """ comment = comments.get_model().objects.create( comment='My Comment', user=self.author, is_public=True, content_object=self.entry, submit_date=timezone.now(), site=self.site) self.assertEqual(len(mail.outbox), 0) moderator = EntryCommentModerator(Entry) moderator.email_authors = True moderator.mail_comment_notification_recipients = [] contributor = Author.objects.create(username='******', email='*****@*****.**') self.entry.authors.add(contributor) moderator.do_email_authors(comment, self.entry, 'request') self.assertEqual(len(mail.outbox), 1) self.assertEqual( set(mail.outbox[0].to), set(['*****@*****.**', '*****@*****.**'])) mail.outbox = [] contributor.email = '' contributor.save() moderator.do_email_authors(comment, self.entry, 'request') self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
def test_integrity_error_on_duplicate_spam_comments(self): class AllIsSpamModerator(EntryCommentModerator): spam_checker_backends = [ 'zinnia.spam_checker.backends.all_is_spam' ] moderator_stack.unregister(Entry) moderator_stack.register(Entry, AllIsSpamModerator) datas = { 'name': 'Jim Bob', 'email': '*****@*****.**', 'url': '', 'comment': 'This is my comment' } f = CommentForm(self.entry) datas.update(f.initial) url = reverse('comments-post-comment') self.assertEqual(self.entry.comment_count, 0) connect_discussion_signals() self.client.post(url, datas) self.client.post(url, datas) disconnect_discussion_signals() self.assertEqual(comments.get_model().objects.count(), 1) entry_reloaded = Entry.objects.get(pk=self.entry.pk) self.assertEqual(entry_reloaded.comment_count, 0)
def items(self): qs = django_comments.get_model().objects.filter( site__pk=self.site.pk, is_public=True, is_removed=False, ) return qs.order_by('-submit_date')[:40]
def delete(request, comment_id, next=None): """ Deletes a comment. Confirmation on GET, action on POST. Requires the "can moderate comments" permission. Templates: :template:`comments/delete.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(django_comments.get_model(), pk=comment_id) # Delete on POST if request.method == 'POST': # Flag the comment as deleted instead of actually deleting it. perform_delete(request, comment) return next_redirect(request, fallback=next or 'comments-delete-done', c=comment.pk) # Render a form on GET else: return render_to_response( 'comments/delete.html', {'comment': comment, "next": next}, template.RequestContext(request) )
def test_count_after_deletion_issue_283(self): comment_klass = comments.get_model() connect_discussion_signals() comment_klass.objects.create(comment='My Comment 1', site=self.site, content_object=self.entry, submit_date=timezone.now()) comment_klass.objects.create(comment='My Comment 2', site=self.site, content_object=self.entry, submit_date=timezone.now()) # It's normal, the signals are not catched on the creation self.assertEqual(self.entry.comment_count, 0) self.entry.comment_count = 2 self.entry.save() comment_klass.objects.all().delete() self.assertEqual(comment_klass.objects.count(), 0) entry_reloaded = Entry.objects.get(pk=self.entry.pk) self.assertEqual(entry_reloaded.comment_count, 0) disconnect_discussion_signals()
def test_comment_success(self): with self.assertNumQueries(0): response = self.client.get('/comments/success/') self.assertTemplateUsed(response, 'comments/zinnia/entry/posted.html') self.assertEqual(response.context['comment'], None) with self.assertNumQueries(1): response = self.client.get('/comments/success/?c=404') self.assertEqual(response.context['comment'], None) comment = comments.get_model().objects.create( submit_date=timezone.now(), comment='My Comment 1', content_object=self.category, site=self.site, is_public=False) success_url = '/comments/success/?c=%s' % comment.pk with self.assertNumQueries(1): response = self.client.get(success_url) self.assertEqual(response.context['comment'], comment) comment.is_public = True comment.save() with self.assertNumQueries(5): response = self.client.get(success_url, follow=True) self.assertEqual( response.redirect_chain[1], ('http://example.com/categories/tests/', 302))
def test_last_child_doesnt_delete_parent(self): Comment = django_comments.get_model() comment = Comment.objects.get(pk=1) new_child_comment = Comment(comment="Comment 9", site_id=1, content_type_id=7, object_pk=1, parent_id=comment.id) new_child_comment.save() new_child_comment.delete() comment = Comment.objects.get(pk=1)
def items(self): """ Items are the discussions on the entries. """ content_type = ContentType.objects.get_for_model(Entry) return comments.get_model().objects.filter( content_type=content_type, is_public=True).order_by( '-submit_date')[:FEEDS_MAX_ITEMS]
def comments_fulltree(request, tree_id, *args, **kwargs): try: comments = get_model().objects.filter_hidden_comments().filter(tree_id=tree_id) comment = comments[0] except IndexError: raise Http404("No top level comment found for tree id %s" % tree_id) cutoff = getattr(settings, 'MPTT_COMMENTS_FULLTREE_CUTOFF', getattr(settings, 'MPTT_COMMENTS_CUTOFF', 3)) + 1 return comments_subtree(request, comment.pk, include_self=True, include_ancestors=True, cutoff=cutoff, *args, **kwargs)
def items(self, page): CommentModel = comments.get_model() return (CommentModel.objects.filter( is_public=True, is_removed=False, content_type=ContentType.objects.get_for_model(Page), object_pk=page.id) .order_by('-submit_date') .prefetch_related('content_object'))
def items(self, page): CommentModel = comments.get_model() return (CommentModel.objects.filter( is_public=True, is_removed=False, content_type=ContentType.objects.get_for_model(Page), object_pk=page.id).order_by('-submit_date').prefetch_related( 'content_object'))
def test_open_and_close_match(self): depth = 0 for x in annotate_tree_properties(django_comments.get_model().objects.all()): depth += getattr(x, 'open', 0) self.assertEqual(x.depth, depth) depth -= len(getattr(x, 'close', [])) self.assertEqual(0, depth)
def items(self): """ Items are the discussions on the entries. """ content_type = ContentType.objects.get_for_model(Entry) return comments.get_model().objects.filter( content_type=content_type, is_public=True).order_by('-submit_date')[:self.limit]
def confirmed(request): comment = None if 'c' in request.GET: try: comment = django_comments.get_model().objects.get(pk=request.GET['c']) except (ObjectDoesNotExist, ValueError): pass return render(request, template, {'comment': comment})
def delete_own_comment(request, message_id): comment = get_object_or_404(django_comments.get_model(), pk=message_id) experience = get_object_or_404(Experience, pk=comment.object_pk) if comment.user == request.user: comment.is_removed = True comment.save() return HttpResponseRedirect( reverse('experiences:experience_detail_slug', args=[experience.id, experience.slug]))
def test_last_flags_set_correctly_only_on_last_sibling(self): # construct the tree nodes = {} for x in django_comments.get_model().objects.all(): nodes[x.pk] = (x, []) if x.parent_id: nodes[x.parent_id][1].append(x.pk) # check all the comments for x in annotate_tree_properties(django_comments.get_model().objects.all()): if getattr(x, 'last', False): # last comments have a parent self.assertTrue(x.parent_id) par, siblings = nodes[x.parent_id] # and ar last in their child list self.assertTrue(x.pk in siblings) self.assertEqual(len(siblings) - 1, siblings.index(x.pk))
def __init__(self, ctype=None, object_pk_expr=None, object_expr=None, as_varname=None, comment=None): if ctype is None and object_expr is None: raise template.TemplateSyntaxError("Comment nodes must be given either a literal object or a ctype and object pk.") self.comment_model = django_comments.get_model() self.as_varname = as_varname self.ctype = ctype self.object_pk_expr = object_pk_expr self.object_expr = object_expr self.comment = comment
def items(self, blog): CommentModel = comments.get_model() post_ids = Post.objects.filter(blog=blog).values_list('id', flat=True) return (CommentModel.objects.filter( is_public=True, is_removed=False, content_type=ContentType.objects.get_for_model(Post), object_pk__in=map(str, post_ids)).order_by( '-submit_date').prefetch_related('content_object'))
def get_comment_model(self): # Provide the model used for comments. When this doesn't match # the sender used by django_comments.moderation.Moderator used in # `comment_will_be_posted.connect(..., sender=...)`, it will break moderation. # # Since ThreadedCommentForm overrides this method, it breaks moderation # with COMMENTS_APP="fluent_comments". Hence, by default let this match # the the model the app is configured with. return django_comments.get_model()
def test_open_and_close_match(self): depth = 0 for x in annotate_tree_properties( django_comments.get_model().objects.all()): depth += getattr(x, 'open', 0) self.assertEqual(x.depth, depth) depth -= len(getattr(x, 'close', [])) self.assertEqual(0, depth)