Example #1
0
    def test_bulk_delete_successfully_deletes_comments(self):
        Comment.objects.bulk_create([
            Comment(user=self.user, thread=self.thread),
            Comment(user=self.user, thread=self.thread),
        ])

        comments = Comment.objects.all()
        Comment.objects.bulk_delete(comments)

        self.assertEqual(Comment.objects.count(), 0)
Example #2
0
 def testListFilteredComments(self):
     movie1 = Movie(title="1")
     movie1.save()
     movie2 = Movie(title="2")
     movie2.save()
     Comment.objects.bulk_create(
         [Comment(movie=movie1, date="2000-01-01") for i in range(2)])
     Comment.objects.bulk_create(
         [Comment(movie=movie2, date="2000-01-01") for i in range(3)])
     response = self.client.get('/comments/', {"id": 1})
     self.assertEqual(200, response.status_code)
     self.assertEqual(2, len(response.json()))
Example #3
0
 def testCommentsOutsideRangeDontCount(self):
     movies = [Movie(title=str(i)) for i in range(4)]
     for m in movies:
         m.save()
     Comment.objects.bulk_create(
         [Comment(movie=movies[0], date="2000-01-02") for j in range(1)])
     Comment.objects.bulk_create(
         [Comment(movie=movies[1], date="2000-01-04") for j in range(2)])
     Comment.objects.bulk_create(
         [Comment(movie=movies[2], date="2000-01-04") for j in range(2)])
     Comment.objects.bulk_create(
         [Comment(movie=movies[3], date="2000-01-04") for j in range(3)])
     ranked = get_ranked_movies("2000-01-01", "2000-01-03")
     self.assertEqual(1, ranked[0]['movie_id'])
Example #4
0
    def handle(self, *args, **options):
        users = list(User.objects.all())

        for i in range(10):
            t = Topic()
            t.name = u'Topic Name {}'.format(i)
            t.description = u'Topic Description {}'.format(i)
            t.save()
        topics = list(Topic.objects.all())

        for j in range(100):
            q = Question()
            q.author = random.choice(users)
            q.title = u'title {}'.format(j)
            q.text = u'text {}'.format(j)
            q.pub_date = datetime.datetime.now()
            q.is_published = True
            q.save()
            q.topics = random.sample(topics, random.randint(1, 6))
        questions = list(Question.objects.all())

        for k in range(100):
            c = Comment()
            c.author = random.choice(users)
            c.question = random.choice(questions)
            c.text = u'text {}'.format(k)
            c.pub_date = datetime.datetime.now()
            c.save()
def bug(request, bugid):
    """
    View for single bug, also handles adding comments to bug
    """
    if request.method == "POST":

        userid = request.user
        comment = request.POST['comment']
        ticket = get_object_or_404(Ticket, pk=bugid)

        if comment == '':
            messages.error(request, 'Comment message is required.')
            return redirect('/tickets/bug/' + bugid)

        comment = Comment(userid=userid, comment=comment, ticketid=ticket)
        comment.save()

        messages.success(request, 'Thanks for your comment.')
        return redirect('/tickets/bug/' + bugid)

    else:

        current_bug = get_object_or_404(Ticket, pk=bugid)
        comments = Comment.objects.all().filter(ticketid=bugid)
        votes = Vote.objects.all().filter(ticket=bugid).count()

        context = {'bug': current_bug, 'comments': comments, 'votes': votes}

        return render(request, 'tickets/bug.html', context)
Example #6
0
File: utils.py Project: ggetzie/nnr
def random_comment(recipe):
    length = random.randint(50, 1000)
    text = "".join([random.choice(string.printable) for _ in range(length)])
    user = random.choice(
        User.objects.filter(is_staff=False, profile__payment_status=3))
    comment = Comment(recipe=recipe, user=user, text=text)
    comment.save()
Example #7
0
def get_experience_details(request, id):
    experience = get_object_or_404(Experience, pk=id)

    experience.views += 1
    experience.save()

    comments = Comment.objects.all()
    comment_list = []

    for comment in comments:
        comment_list = Comment.objects.all().order_by('-pub_date').filter(
            experience__id=experience.id)

    # add comment
    form = CommentForm(request.POST)
    user = request.user

    if form.is_valid() and user.is_authenticated:
        content = form.cleaned_data['content']
        comment = Comment()
        comment.experience_id = experience.id
        comment.content = content
        comment.save()
        return HttpResponseRedirect(
            reverse('get_experience_details', args=(experience.id, )))

    contexts = {
        'experience': experience,
        'form': form,
        'comment_list': comment_list
    }

    return render(request, 'experience_details.html', contexts)
Example #8
0
def test_put_instance_if_anonymous(req):

    req.method = 'PUT'
    req.user = AnonymousUser()

    perm = CommentPermission()
    assert not perm.has_object_permission(req, mock.Mock(), Comment())
Example #9
0
    def create(self, validated_data):
        comment = validated_data['comment']
        movie_id = validated_data['movie_id']

        # print(validated_data)
        # # Get movie object
        try:
            movie = Movie.objects.get(id=movie_id)
        except Movie.DoesNotExist:
            raise serializers.ValidationError(
                'Thread does not exist, please enter correct thread id')

        # # Get the requesting user
        user = None
        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user
        else:
            raise serializers.ValidationError(
                'Must be authenticated to create post')

        # Create the post
        comment = Comment(comment=comment, movie=movie, user=user)
        # print(comment)
        # Update the thread last_activity to post creation time
        comment.save()
        return comment
Example #10
0
def show(request, production_id, edit_mode=False):
	production = get_object_or_404(Production, id=production_id)
	if production.supertype != 'music':
		return HttpResponseRedirect(production.get_absolute_url())

	if request.user.is_authenticated():
		comment = Comment(commentable=production, user=request.user)
		comment_form = CommentForm(instance=comment, prefix="comment")
		tags_form = ProductionTagsForm(instance=production)
	else:
		comment_form = None
		tags_form = None

	return render(request, 'productions/show.html', {
		'production': production,
		'download_links': production.download_links,
		'external_links': production.external_links,
		'credits': production.credits_for_listing(),
		'carousel': Carousel(production, request.user),
		'featured_in_productions': [
			appearance.production for appearance in
			production.appearances_as_soundtrack.select_related('production', 'production__default_screenshot').order_by('production__release_date_date')
		],
		'packed_in_productions': [
			pack_member.pack for pack_member in
			production.packed_in.select_related('pack', 'pack__default_screenshot').order_by('pack__release_date_date')
		],
		'competition_placings': production.competition_placings.order_by('competition__party__start_date_date'),
		'invitation_parties': production.invitation_parties.order_by('start_date_date'),
		'release_parties': production.release_parties.order_by('start_date_date'),
		'tags': production.tags.order_by('name'),
		'blurbs': production.blurbs.all() if request.user.is_staff else None,
		'comment_form': comment_form,
		'tags_form': tags_form,
	})
def seed_comments():
    comments_count = db.session.query(func.count(Comment.id)).scalar()
    comments_to_seed = 31
    comments_to_seed -= comments_count
    sys.stdout.write('[+] Seeding %d comments\n' % comments_to_seed)
    comments = []

    user_ids = [user[0] for user in User.query.with_entities(User.id).all()]
    product_ids = [
        product[0] for product in Product.query.with_entities(Product.id)
    ]
    # equivalent:
    # user_ids = [user[0] for user in db.session.query(User.id).all()]
    # product_ids = [product[0] for product in db.session.query(Product.id).all()]

    for i in range(comments_count, comments_to_seed):
        user_id = random.choice(user_ids)
        product_id = random.choice(product_ids)
        rating = fake.random_int(min=1, max=5) if fake.boolean(
            chance_of_getting_true=50) else None
        comments.append(
            Comment(product_id=product_id,
                    user_id=user_id,
                    rating=rating,
                    content=fake.paragraph(nb_sentences=4,
                                           variable_nb_sentences=True,
                                           ext_word_list=None)))

    db.session.add_all(comments)
    db.session.commit()
Example #12
0
def seed_comments():
    comments_count = db.session.query(func.count(Comment.id)).scalar()
    comments_to_seed = 31
    comments_to_seed -= comments_count
    sys.stdout.write('[+] Seeding %d comments\n' % comments_to_seed)
    comments = []

    user_ids = [user[0] for user in User.query.with_entities(User.id).all()]
    article_ids = [
        article[0] for article in Article.query.with_entities(Article.id)
    ]
    # equivalent:
    # user_ids = [user[0] for user in db.session.query(User.id).all()]
    # article_ids = [article[0] for article in db.session.query(Article.id).all()]

    for i in range(comments_count, comments_to_seed):
        user_id = random.choice(user_ids)
        article_id = random.choice(article_ids)
        comments.append(
            Comment(article_id=article_id,
                    user_id=user_id,
                    content=faker.sentence()))

    db.session.add_all(comments)
    db.session.commit()
Example #13
0
def displayPost(request, username, post_number):
    post = Post.objects.get(user=User.objects.get(username=username),
                            id=post_number)
    comments = Comment.objects.filter(post=post)

    # generate or handle comment form.
    if request.method == "POST":
        comment_text = request.POST.get('the_comment')
        comment = Comment(body=comment_text, post=post, user=request.user)
        comment.save()
        user = request.user.username
        num_comments = post.comment_set.count()
        response_data = {
            'comment': str(comment),
            'comment_id': comment.id,
            'user': user,
            'comment_count': num_comments
        }
        return JsonResponse(response_data)
    else:
        comment_form = CommentForm()
        reply_form = ReplyForm()

    num_comments = post.comment_set.count()
    context = {
        'post': post,
        'comments': comments,
        'num_comments': num_comments,
        'comment_form': comment_form,
        'reply_form':
        reply_form  # not initially in template. generated via ajax call if user clicks on reply link.
    }
    return render(request, 'posts/single_post.html', context)
def bug(request, bugid):
    """
    View the details of a specific bug
    """
    user = request.user
    if user.is_authenticated:
        if request.method == "POST":
            user = request.user
            comment = request.POST['comment']
            ticket = get_object_or_404(Ticket, pk=bugid)
            if comment.strip() == '':
                messages.error(request, 'Comment message is required.')
                return redirect('bug', bugid=ticket.pk)

            comment = Comment(user=user, comment=comment, ticket=ticket)
            comment.save()
            messages.success(request, 'Thanks for your comment.')
            return redirect('bug', bugid=ticket.pk)

    current_bug = get_object_or_404(Ticket, pk=bugid)
    comments = Comment.objects.all().filter(ticket=bugid)
    votes = Vote.objects.all().filter(ticket=bugid).count()
    context = {
        'bug': current_bug,
        'comments': comments,
        'votes': votes
    }
    return render(request, 'bug.html', context)
Example #15
0
 def create_user_and_content(self, is_index_dirty=True):
     user = User.objects.create_user("testuser", password="******")
     # Create comments
     target_sound = Sound.objects.all()[0]
     for i in range(0, 3):
         comment = Comment(comment="Comment %i" % i,
                           user=user,
                           content_object=target_sound)
         target_sound.add_comment(comment)
     # Create threads and posts
     thread = Thread.objects.create(
         author=user,
         title="Test thread",
         forum=Forum.objects.create(name="Test forum"))
     for i in range(0, 3):
         Post.objects.create(author=user,
                             thread=thread,
                             body="Post %i body" % i)
     # Create sounds and packs
     pack = Pack.objects.create(user=user, name="Test pack")
     for i in range(0, 3):
         Sound.objects.create(user=user,
                              original_filename="Test sound %i" % i,
                              pack=pack,
                              is_index_dirty=is_index_dirty,
                              license=License.objects.all()[0],
                              md5="fakemd5%i" % i,
                              moderation_state="OK",
                              processing_state="OK")
     return user
Example #16
0
 def post_handler(request):
     # JSON post body of what you post to a posts' comemnts
     # POST to http://service/posts/{POST_ID}/comments
     output = {
         "query": "addComment",
     }
     # change body = request.POST to body = request.body.decode('utf-8'),
     # because request.POST only accepts form, but here is json format.
     # change new_comment.comment to new_comment.content,
     # because that's how it defined in comment model.
     
     try:
         body = request.body.decode('utf-8')
         comment_info = loads(body)
         comment_info = comment_info['comment']
         new_comment = Comment()
         new_comment.contentType = comment_info['contentType']
         new_comment.content = comment_info['comment']
         new_comment.published = comment_info['published']
         new_comment.author = Author.objects.filter(id=comment_info['author']['id']).first()
         new_comment.parentPost = Post.objects.filter(id=post_id).first()
         new_comment.save()
         output['type'] = True
         output['message'] = "Comment added"
     except Exception as e:
         output['type'] = False
         output['message'] = "Comment not allowed"
         output['error'] = str(e)
     finally:
         return JsonResponse(output)
Example #17
0
def comment_create(request, slug):
    try:
        item = Item.objects.get(slug=slug)
    except Item.MultipleObjectsReturned:
        item = item.objects.filter(slug=slug).last()
    except Item.DoesNotExist:
        item = None
    if request.method == 'POST':
        if request.user.is_authenticated and request.user.is_customer():
            response_data = {}
            data = request.POST['comment']
            comment = Comment()
            comment.comment = data
            comment.fiscal_year = FiscalYear.get_active_fiscal_year()
            comment.item = item
            comment.user = request.user
            comment.save()

            response_data['result'] = 'Create post successful!'
            response_data['postpk'] = str(comment.pk)
            response_data['comment'] = str(comment.comment)
            response_data['created'] = str(comment.created_at)
            response_data['image'] = str(request.user.userprofile.pic)
            response_data['author'] = str(comment.user.full_name)
            return JsonResponse(response_data)
    else:
        return JsonResponse({'data': 'hello owrld'})
Example #18
0
def detail_view(request, slug):
    cart = Cart.objects.get_cart(request)
    query = get_object_or_404(Product, slug=slug)
    com = query.comments.all()
    if request.method == 'POST':
        if request.user.is_authenticated:
            comment = request.POST.get('comment', None)
            rating = request.POST.get('option', None)
            if comment is not None and rating is not None:
                new_comment = Comment(content=comment,
                                      author=request.user,
                                      rating=rating)
                new_comment.save()
                query.comments.add(new_comment)

        var = request.POST.get('foo')
        if var == 'remove':
            cart.product.remove(query)
        if var == 'add':
            cart.product.add(query)
    if query in cart.product.all():
        change = 1
    else:
        change = 2

    print(request.POST)
    context = {
        'qs': query,
        'com': com,
        'cart': cart,
        'change': change,
        'comm_access': comment_is_access(request, qery)
    }
    return render(request, 'shop/detail_view.html', context)
Example #19
0
def test_get_instance_if_authenticated(req):

    req.method = 'GET'
    req.user = User()

    perm = CommentPermission()
    assert perm.has_object_permission(req, mock.Mock(), Comment())
Example #20
0
def new(request):
    if not request.user.is_authenticated():
        return HttpResponseForbidden

    user = request.user

    data = json.loads(request.body.decode('utf-8'))
    review = get_object_or_404(Review, id=data['reviewId'])
    comment = Comment(body=data['body'],
                      user=user,
                      review=review,
                      user_name=("%s %s" % (user.first_name, user.last_name)))

    try:
        comment.save()
    except:
        return HttpResponseBadRequest()

    return JsonResponse(
        {
            'userName': comment.user_name,
            'userId': comment.user_id,
            'reviewId': comment.review_id,
            'body': comment.body
        },
        safe=False)
Example #21
0
 def update_comment(self):
     """
     Creates the shadow comment object to hold this document's place in a
     commment thread, if this document is a reply to comments.
     """
     # Create comment objects only when the doc is public.  That way,
     # subscription signals are fired at the right moment -- the comment is
     # public and viewable.
     parent = None
     if self.in_reply_to:
         try:
             parent = self.in_reply_to.document
         except Document.DoesNotExist:
             pass
     if parent and self.is_public():
         # Only create a comment object if we are public.
         try:
             comment = self.comment
         except Comment.DoesNotExist:
             comment = Comment()
         comment.user = self.author
         comment.removed = False
         comment.document = parent
         comment.comment_doc = self
         comment.save()
     else:
         # If we've gone non-public, mark the comment removed rather
         # than deleting.  That way, we don't re-fire subscriptions if
         # the doc is only temporarily un-published.
         try:
             self.comment.removed = True
             self.comment.save()
         except Comment.DoesNotExist:
             pass
Example #22
0
    def migrate_comments(self):

        for legacy_comment in LegacyComment.objects.all():
            assert isinstance(legacy_comment, LegacyComment)

            date_naive = datetime.utcfromtimestamp(legacy_comment.timestamp)
            date = timezone.make_aware(date_naive, timezone.utc)

            comment = Comment()
            comment.body = legacy_comment.comment
            comment.created = date
            comment.public = not legacy_comment.officer

            comment.user_id = legacy_comment.poster_id  # this is erroring

            if legacy_comment.section == 0:
                continue
            if legacy_comment.section == 1:
                continue
            if legacy_comment.section == 2:
                continue
            if legacy_comment.section == 5:
                continue

            comment.content_type_id = {  # i dont know what the keys are for the different content types
                0: 1,  # user manager
                1: 2,  # application
                2: 3,  # fodder vote
                3: 4,  # quote
                4: 5,  # screenshot
                5: 6  # leadership application
            }.get(legacy_comment.section)

            comment.object_id = legacy_comment.reference
            comment.save()
Example #23
0
def comment_post(request, boardno, userid, text):
    user = get_object_or_404(User, id=userid)
    board = get_object_or_404(Board, id=boardno)
    comment = Comment(text=text, writer=user, board=board)
    print(comment)
    comment.save()
    return Response({"message": "data input!", "data": request.data})
Example #24
0
    def test_blog_comments_view_comment(self, comment):
        blog_post = Post(title='Sample post',
                         content='Sample content',
                         author=self.user_with_blog,
                         status='p',
                         blog=self.user_with_blog.blog)
        blog_post.save()
        if comment:
            comment = Comment(author=self.user_with_blog,
                              post=blog_post,
                              comment='test comment')
            comment.save()
            comment_count = 1
        else:
            comment_count = 0

        self.assertTrue(
            self.client.login(username='******',
                              password='******'))

        target = reverse('blog:blog_comments')
        response = self.client.get(target)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'blog/comments_list.html')
        self.assertEqual(response.context['comments'].count(), comment_count)
Example #25
0
    def post(self, request):
        try:
            user = request.user
        except Account.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        serializer = CreateCommentSerializer(data=request.data)
        if serializer.is_valid():
            try:
                post = Post.objects.get(slug=request.data.get('post'))
            except Post.DoesNotExist:
                return Response(status=status.HTTP_404_NOT_FOUND)
            parent_comment = serializer.data.get('parent_comment', None)
            if parent_comment:
                try:
                    parent_comment = Comment.objects.get(id=parent_comment_id)
                except Comment.DoesNotExist:
                    parent_comment = None
            comment = Comment()
            comment.body = serializer.data.get('body')
            comment.post = post
            comment.author = user
            comment.parent_comment = parent_comment
            comment.save()
            return Response(data=DetailCommentSerializer(comment).data,
                            status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #26
0
    def create_user_and_content(self):
        user = User.objects.create_user("testuser", password="******")
        # Create comments
        target_sound = Sound.objects.all()[0]
        for i in range(0, 3):
            comment = Comment(comment="Comment %i" % i,
                              user=user,
                              content_object=target_sound)
            target_sound.add_comment(comment)
        # Create threads and posts
        thread = Thread.objects.create(
            author=user,
            title="Test thread",
            forum=Forum.objects.create(name="Test forum"))
        for i in range(0, 3):
            Post.objects.create(author=user,
                                thread=thread,
                                body="Post %i body" % i)
        # Create deleted sounds
        for i in range(0, 3):
            DeletedSound.objects.create(user=user,
                                        sound_id=i)  # Using fake sound id here
        # Create sounds and packs
        pack = Pack.objects.create(user=user, name="Test pack")
        for i in range(0, 3):
            Sound.objects.create(user=user,
                                 original_filename="Test sound %i" % i,
                                 pack=pack,
                                 license=License.objects.all()[0],
                                 md5="fakemd5%i" % i)

        return user
    def sync_comment(self):
        comments_map = {}
        root_header = None
        root_comment = None

        for comment in self.comments():
            dot()
            if root_header is None or root_header.object_id != comment.nid:
                root_comment = Comment.objects.get_or_create_root_comment(
                    self.node_ctype, comment.nid)[0]
            update_comments_header(Comment, instance=root_comment)
            filters = self.formats_filtering.get(comment.format,
                                                 self.formats_filtering[1])
            filtered_comment = self.call_filters(comment.comment, filters)
            time_created = timestamp_to_time(comment.timestamp)
            comment_instance = Comment(
                parent_id=comments_map[comment.pid]
                if comment.pid else root_comment.id,
                object_id=comment.nid,
                content_type=self.node_ctype,
                subject=comment.subject,
                created=time_created,
                updated=time_created,
                user_id=self.users_map.get(comment.uid),
                user_name=comment.name,
                is_public=True,
                is_locked=root_comment.is_locked,
                original_comment=TextVal(
                    self.filter_formats.get(comment.format, 'raw') + ':' +
                    comment.comment),
            )
            comment_instance.save()
            Comment.objects.filter(pk=comment_instance.pk).update(
                filtered_comment=filtered_comment)
            comments_map[comment.cid] = comment_instance.pk
Example #28
0
def art_comment(request, art_pk):
	#art = models.Art.objects.filter(id=int(art_pk))   #方法1
	art = get_object_or_404(models.Art, pk=art_pk)     #方法2
	if request.method == "POST":
		form = CommentForm(data=request.POST)
		if form.is_valid():  #评论表单合法
			cmt = Comment(name=form.cleaned_data['name'],
						  title=form.cleaned_data['title'],
						  text=form.cleaned_data['text'],
						  art=art)
			cmt.save()
			comment_list = art.comment_set.all()  #通过外键反查所有评论
			comment_count = comment_list.count(),
			context = dict(
				art=art,
				form=form,
				comment_list=comment_list,
				comment_count=comment_count,
			)
			return render(request, "detail_handler.html", context=context)
		else:
			comment_list = art.comment_set.all()  # 通过外键反查所有评论
			comment_count = comment_list.count(),
			context = dict(
				art=art,
				form=form,
				comment_list=comment_list,
				comment_count=comment_count,
			)
			flash(request, "error", "用户提交评论失败!")
			return render(request, "detail_handler.html", context=context)

	return redirect(art)
Example #29
0
 def setUp(self):
     self.user = UserFactory()
     self.client = APIClient()
     self.client.force_authenticate(user=self.user)
     self.list_url = reverse('api:activity-list')
     # create a bunch of action objects of various types
     self.team = TeamFactory()
     self.team_member = TeamMemberFactory(user=self.user, team=self.team)
     self.video = VideoFactory()
     TeamVideoFactory(video=self.video, team=self.team)
     self.user2 = UserFactory()
     Action.create_video_handler(self.video, self.user)
     self.video.title = 'new-title'
     self.video.save()
     Action.change_title_handler(self.video, self.user)
     # creating comment will automatically create the action object
     Comment(content_object=self.video,
             user=self.user,
             content="Test Comment").save()
     v = pipeline.add_subtitles(self.video, 'en', None, author=self.user)
     Action.create_caption_handler(v, datetime.now())
     Action.create_approved_video_handler(v, self.user2)
     Action.create_rejected_video_handler(v, self.user2)
     Action.create_new_member_handler(self.team_member)
     Action.create_member_left_handler(self.team, self.user)
     self.action_qs = Action.objects.for_user(self.user)
def post_detail(request, postid):
    """
    Returns a single Post object based on the post ID (pk) and render
    it to the 'postdetail.html' template.
    Return a 404 error if the post is not found.
    """
    user = request.user
    if user.is_authenticated:
        if request.method == "POST":
            user = request.user
            comment = request.POST['comment']
            post = get_object_or_404(Post, pk=postid)
            if comment.strip() == '':
                messages.error(request, 'Comment message is required.')
                return redirect('post_detail', postid=post.pk)

            comment = Comment(user=user, comment=comment, post=post)
            comment.save()
            messages.success(request, 'Thanks for your comment.')
            return redirect('post_detail', postid=post.pk)

    current_post = get_object_or_404(Post, pk=postid)
    current_post.views += 1
    current_post.save()
    comments = Comment.objects.all().filter(post=postid)
    context = {
        'post': current_post,
        'comments': comments,
    }
    return render(request, 'postdetail.html', context)