Пример #1
0
def post_detail(request, id):
    if request.method == "POST":
        comment = request.POST['comment']
        user = User.objects.get(username=request.user.username)
        c = Comment(comment_text=comment, post_id=id, user=user)
        c.save()
        return redirect('post', id)
    else:
        template_name = "blog/post.html"
        post = Post.objects.get(id=int(id))
        comments = Comment.objects.filter(post=post)
        context = {'post': post, 'comments': comments}
        return render(request, template_name, context)
Пример #2
0
def post_detail(request, pk):
    if request.method == "POST":
        comment = request.POST['comment']
        user = User.objects.get(username=request.user.username)
        c = Comment(comment_text=comment, post_id=pk, user=user)
        c.save()
        return redirect("post", pk)
    else:
        template_name = 'blog/view.html'
        post = Post.objects.get(id=int(pk))
        comment = Comment.objects.filter(post=post)
        context = {'post': post, 'comment':comment}
        return render(request, template_name, context)
Пример #3
0
def blog_detail(request, pk):
    post = Post.objects.get(pk=pk)
    comments = Comment.objects.filter(post=post)
    form = CommentForm()
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(author=form.cleaned_data["author"],
                              body=form.cleaned_data["body"],
                              post=post)
            comment.save()
    context = {"post": post, "comments": comments, "form": form}
    return render(request, "blog_detail.html", context)
Пример #4
0
def comment(request, article_id):
    if not request.POST['author'] or not request.POST['text']:
        request.message = "vous avez oubliez une partie du commentaire non?"
        return detail(request, article_id)
    else:
        request.message = "commentaire enregistre!"
    comment = Comment()
    comment.author = request.POST['author']
    comment.text = request.POST['text']
    comment.date = timezone.now()
    comment.article = Article.objects.get(id=article_id)
    comment.save()
    return detail(request, article_id)
Пример #5
0
def show_post(post_id):
    post = Post.query.get_or_404(post_id)  #没有找到返回404
    page = request.args.get('page', 1, type=int)
    per_page = current_app.config['BLUELOG_COMMENT_PER_PAGE']
    pagination = Comment.query.with_parent(post).filter_by(
        reviewed=True).order_by(Comment.timestamp.asc()).paginate(
            page, per_page)
    comments = pagination.items

    if current_user.is_authenticated:
        form = AdminCommentForm()
        form.author.data = current_user.name
        form.email.data = current_app.config['BLUELOG_ADMIN_EMAIL']
        form.site.data = url_for('.index')
        from_admin = True
        reviewed = True
    else:
        form = CommentForm()
        from_admin = False
        reviewed = False

    if form.validate_on_submit():
        author = form.author.data
        email = form.email.data
        site = form.site.data
        body = form.site.data
        comment = Comment(author=author,
                          email=email,
                          site=site,
                          body=body,
                          from_admin=from_admin,
                          post=post,
                          reviewed=reviewed)
        replied_id = request.args.get('reply')
        if replied_id:
            replied_comment = Comment.query.get_or_404(replied_id)
            comment.replied = replied_comment
            # send_new_comment_email(replied_comment)
        db.session.add(comment)
        db.session.commit()
        if current_user.is_authenticated:
            flash('评论完成', 'success')
        else:
            flash('谢谢评论,稍后审核', 'info')
            # send_new_comment_email(post)
        return redirect(url_for('.show_post', post_id=post_id))
    return render_template('blog/post.html',
                           post=post,
                           pagination=pagination,
                           comments=comments,
                           form=form)
Пример #6
0
    def post(self, slug):
        context = self.get_context(slug)
        form = context.get('form')

        if form.validate():
            comment = Comment()
            form.populate_obj(comment)

            post = context.get('post')
            post.comments.append(comment)
            post.save()

            return redirect(url_for('posts.detail', slug=slug))
        return render_template('posts/detail.html', **context)
Пример #7
0
def blog_detail(request, pk):
    post = Post.objects.get(pk=pk)
    comments = Comment.objects.filter(post=post)

    form = CommentForm()
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(
                author=form.cleaned_data["author"],
                body=form.cleaned_data["body"],
                post=post,
            )
            comment.save()
Пример #8
0
def create_comment(request):
    new_comment = Comment()
    article_id = request.POST['article']
    article = Article.objects.get(pk=article_id)

    new_comment.name = request.POST['name']
    new_comment.message = request.POST['message']
    new_comment.article = article  #Sets the foreign key as the article object.

    new_comment.save()

    context = {'article': article}
    response = render(request, 'article.html', context)
    return HttpResponse(response)
Пример #9
0
def article(slug):
    form = CommentForm()
    if form.validate_on_submit():
        post = Post.query.filter_by(slug=slug).first_or_404()
        author = Author.query.filter_by(username=session['username']).first()
        body = form.body.data
        timestamp = datetime.utcnow()
        comment = Comment(post, author, body, timestamp)
        db.session.add(comment)
        db.session.commit()
        flash("Comment posted.")
        return redirect(url_for('article', slug=post.slug))
    post = Post.query.filter_by(slug=slug).first_or_404()
    return render_template('blog/article.html', form=form, post=post)
Пример #10
0
def blog_detail(request, pk):
    print("AAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
    all_posts = Post.objects.all().order_by('-created_on')

    prevVal = None
    nextVal = None
    for i, item in enumerate(all_posts):
      if item.pk == pk:
          if (i > 0):
              prevVal = all_posts[i-1].pk
          if (i < len(all_posts)-1):
              nextVal = all_posts[i+1].pk

    post = Post.objects.get(pk=pk)
    new_comment = False
    tryToPost = False
    form = CommentForm()

    if request.method == 'POST':
        tryToPost = True
        print("IT IS A POST")
        response=grecaptcha_verify(request)
        if response == True :
            form = CommentForm(request.POST)
            if form.is_valid():

                comment = Comment(
                    author=form.cleaned_data["author"],
                    body=form.cleaned_data["body"],
                    post=post
                )
                comment.save()
                new_comment = True
            else:
                form = CommentForm()
                print("Form is not valid")
        else:
            print("CAPTCHA IS FAILING")

    comments = Comment.objects.filter(post=post)
    context = {
        "post": post,
        "comments": comments,
        "form": form,
        "new_comment": new_comment,
        "prevVal": prevVal,
        "nextVal": nextVal,
        "tryToPost": tryToPost
    }
    return render(request, "blog_detail.html", context)
Пример #11
0
    def setUp(self):
        super(BlogTestCase, self).setUp()
        self.login()

        category = Category(name='Default')
        post = Post(title='Hello Post', category=category, body='Blah...')
        comment = Comment(body='A comment',
                          post=post,
                          from_admin=True,
                          reviewed=True)
        link = Link(name='GitHub', url='https://github.com/greyli')

        db.session.add_all([category, post, comment, link])
        db.session.commit()
Пример #12
0
def add_comment(request, blog_id):
    form = CommentForm(request.POST)
    post = get_object_or_404(Blog, pk=blog_id)
    if form.is_valid():
        author = form.cleaned_data['author']
        content = form.cleaned_data['content']
        new_comment = Comment(id=None,
                              author=author,
                              content=content,
                              post_id=post)
        new_comment.save()
        messages.success(request, "Comment has been added.")
        return redirect('detail', blog_id=blog_id)
    return render(request, "main/comment_form.html", {'form': form})
Пример #13
0
def fake_comment(count=200):
    for i in range(count):
        comment = Comment(
            author=User.query.get(random.randint(1, User.query.count())),
            body=fake.sentence(),
            timestamp=fake.date_time_this_year(),
            article=Article.query.get(random.randint(1,
                                                     Article.query.count())))
        db.session.add(comment)

    salt = int(count * 0.1)
    # replies
    for i in range(salt):
        comment = Comment(
            author=User.query.get(random.randint(1, User.query.count())),
            body=fake.sentence(),
            timestamp=fake.date_time_this_year(),
            replied=Comment.query.get(random.randint(1,
                                                     Comment.query.count())),
            article=Article.query.get(random.randint(1,
                                                     Article.query.count())))
        db.session.add(comment)
    db.session.commit()
Пример #14
0
def blog_detail(request, pk):
    """ Display an individual blog post. Provides a form below the post
        for guests to leave comments. Guests must solve a reCAPTCHA before
        being allowed to submit their comment.
    """
    site_key = open('/var/www/project/recaptcha_site', 'r').read()
    secret_key = open('/var/www/project/recaptcha_secret', 'r').read()
    post = Post.objects.get(pk=pk)
    comments = Comment.objects.filter(post=post)

    form = CommentForm()
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():

            ''' Begin reCAPTCHA validation '''
            recaptcha_response = request.POST.get('g-recaptcha-response')
            url = 'https://www.google.com/recaptcha/api/siteverify'
            values = {
                'secret': secret_key,
                'response': recaptcha_response
            }
            data = urllib.parse.urlencode(values).encode()
            req = urllib.request.Request(url, data=data)
            response = urllib.request.urlopen(req)
            result = json.loads(response.read().decode())
            ''' End reCAPTCHA validation '''

            if result['success']:
                comment = Comment(
                    author=form.cleaned_data["author"],
                    body=form.cleaned_data["body"],
                    post=post,
                )
                comment.save()
                messages.success(request, 'Comment added successfully!')
            else:
                messages.error(request, 'Invalid reCAPTCHA. Please try again.')

            return redirect('blog_detail', pk)

    title = post.title
    context = {
        "title": title,
        "post": post,
        "comments": comments,
        "form": form,
        "site_key": site_key
    }
    return render(request, "blog_detail.html", context)
Пример #15
0
def new_comment(post_id):
    comments = Comment.query.filter_by(post_id=post_id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(comment=form.comment.data, post_id=post_id)

        db.session.add(comment)
        db.session.commit()
        flash('Your comment has been added', 'success')
        return redirect(url_for('home'))
    return render_template('new_comment.html',
                           title="New Comment",
                           form=form,
                           comments=comments)
Пример #16
0
 def test_delete_comment_unauthenticated(self):
     item = Comment()
     item.post = self.setup_comment_test()
     item.author = "No Auth Author 1"
     item.text = "No Auth Text 1"
     item.save()
     self.assertEqual(Comment.objects.count(), 1)
     new_item = Comment.objects.first()
     url = "/blog/comment/" + str(new_item.pk) + "/remove/"
     response = self.client.get(url)
     self.assertEqual(Comment.objects.count(), 1)
     self.assertNotEqual(response['location'],
                         "/blog/post/" + str(item.post.pk))
     self.assertEqual(response['location'], "/accounts/login/?next=" + url)
Пример #17
0
def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        comment = Comment(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = CommentForm()

    return render(request, 'blog/comment_form.html', context={'form': form})
Пример #18
0
def comment(post_id):
    form = CommentForm()
    post = Post.query.filter_by(id=post_id).first_or_404()

    if form.validate_on_submit():
        author = Author.query.filter_by(username=session['username']).first()
        body = form.body.data
        comment = Comment(post, author, body)
        db.session.add(comment)
        db.session.flush()
        db.session.commit()
        flash("Blog post commented")
        return redirect(url_for('article', slug=post.slug))
    return render_template('blog/comment.html', form=form, post=post)
Пример #19
0
    def setup_visible_test(self):
        item = Post()
        item.title = "No Auth Base Post"
        item.subtitle = "No Auth Base Subtitle"
        item.text = "No Auth Base Text"
        item.author = self.user
        item.save()

        item2 = Comment()
        item2.post = item
        item2.author = "No Auth Base Author"
        item2.text = "No Auth Base Text"
        item2.save()
        return item, item2
Пример #20
0
def viewPost(request, year, month, title):
    post = Post.objects.get(title=title)
    recent_posts = Post.objects.filter(
        date__lte=timezone.now()).order_by('-date')[:10]

    comments = Comment.objects.filter(post=post)
    reply_comment = None

    if request.method == 'POST':
        username = request.POST['username']
        email = request.POST['email']
        message = request.POST['message']
        reply_id = -1

        if request.POST['reply_comment'] != "":
            reply_id = request.POST['reply_comment']

        comment = Comment(post=post,
                          username=username,
                          email=email,
                          message=message,
                          reply_id=reply_id,
                          date=timezone.now())
        comment.save()

        post.comments += 1
        post.save()

        return render(request, 'blog/view/post.html', {
            'post': post,
            'posts': recent_posts,
            'comments': comments,
        })
    else:
        reply_id = request.GET.get('replyTo', None)

        if reply_id is not None:
            for comment in comments:
                if str(reply_id) == str(comment.id):
                    reply_comment = comment

        # Passing an array so the if will need to use |length than count
        return render(
            request, 'blog/view/post.html', {
                'post': post,
                'posts': recent_posts,
                'comments': comments,
                'reply_comment': reply_comment,
            })
Пример #21
0
    def post(self, request, *args, **kwargs):
        check_result = self.check_value(("article_id", u"文章id有误"), ("name", u"昵称不能为空"), ("content", u"评论内容不能为空"))
        if check_result:
            res = codedesc.JSON_ERR
            res["msg"] = check_result
            return JsonResponse(res)
        article_id = self.json_data.get("article_id")
        parent_comment_id = self.json_data.get("parent_comment_id")
        email = self.json_data.get("email")
        name = self.json_data.get("name")
        if len(name) > 20:
            res = codedesc.JSON_ERR
            res["msg"] = u"昵称太长, 不能超过20个字符"
            return JsonResponse(res)
        content = self.json_data.get("content")
        if len(content) > 1024:
            res = codedesc.JSON_ERR
            res["msg"] = u"评论内容太长, 不能超过1024个字符"
            return JsonResponse(res)
        article = Article.objects.filter(id=article_id).first()
        if not article:
            res = codedesc.JSON_ERR
            res["msg"] = u"article_id error"
            return JsonResponse(res)

        new_comment = Comment(name=name, content=content, email=email)
        new_comment.save()
        article.comments.add(new_comment)
        if parent_comment_id:
            parent_comment = Comment.objects.filter(id=parent_comment_id).first()
            if not parent_comment:
                res = codedesc.JSON_ERR
                res["msg"] = u"parent_comment_id error"
                return JsonResponse(res)
            new_comment.parent_comment = new_comment
            new_comment.save()
            parent_comment.replys.add(new_comment)

        request.session["name"] = name
        request.session["email"] = email
        res = codedesc.OK
        res["article_id"] = article_id
        res["comment_id"] = new_comment.id
        res["comment_time"] = timezone.make_naive(new_comment.create_time).strftime("%Y-%m-%d %H:%M:%S")
        if parent_comment_id:
            res["comment_first"] = u"@%s: " % parent_comment.name
        else:
            res["comment_first"] = ""
        return JsonResponse(res)
Пример #22
0
def blog_show(request, pk):
    post = Post.objects.get(pk=pk)

    form = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(author=form.cleaned_data['author'],
                              body=form.cleaned_data['body'],
                              post=post)
            comment.save()

    comments = Comment.objects.filter(post=post)
    context = {'post': post, 'comments': comments, 'form': form}
    return render(request, 'blog_show.html', context)
Пример #23
0
def post(post_id):
    post = Post.query.get_or_404(post_id)
    form = CommentForm()
    comments = Comment.query.all()
    if form.validate_on_submit():
        comment = Comment(content=form.content.data)
        db.session.add(comment)
        db.session.commit()
        flash('Your comment has been posted!', 'primary')
        return redirect(url_for('home'))
    return render_template('blog.html',
                           title=post.title,
                           post=post,
                           form=form,
                           comments=comments)
Пример #24
0
def addComment(request, postId):
	print "Add comment url visited"
	if request.method == 'POST':
		print "Post request received"
		form = CommentForm(request.POST)
		if form.is_valid():
			newComment = Comment()
			newComment.post = Blog.objects.get(id=postId)		
			newComment.body = form.cleaned_data['body']
			newComment.created_by = form.cleaned_data['created_by']
			newComment.save()
			print "Comment saved"
		else:
			print form.errors
	return viewPost(request, postId)
Пример #25
0
def comm_edit(request, postno, comno):
    post = Post.objects.get(id=postno)
    c = Comment.objects.get(id=comno)
    if request.user.username != post.user.username:
        raise PermissionDenied
    if request.method == "GET":
        template = 'blog/editcom.html'
        context = {"comment": c, "post": post}
        return render(request, template, context)
    else:
        comm = request.POST['comment']
        user = User.objects.get(username=request.user.username)
        com = Comment(id=comno, comment_text=comm, user=user, post_id=postno)
        com.save()
        return redirect('post', postno)
Пример #26
0
 def post(self, request, article_id):
     """
     以post提交是处理评论的
     """
     post = Post.objects.filter(id=article_id).first()
     form = forms.CommentForm(request.POST)
     if form.is_valid():
         comment = form.cleaned_data['comment']
         name = form.cleaned_data['name']
         if not name:
             name = '无名氏'
         comment = Comment(name=name, text=comment, post=post)
         comment.save()
     url = reverse('blog:article', kwargs={'article_id': article_id})
     return redirect(url)
Пример #27
0
def add_comment(request, pk):
    """Add a new comment to a given post"""
    p = request.POST

    if p.has_key('body') and p['body']:
        author = p.get('author', 'Anonymous')

        comment = Comment(post=get_object_or_404(Post, pk=pk))
        cf = CommentForm(p, instance=comment)
        cf.fields["author"].required = False

        comment = cf.save(commit=False)
        comment.author = author
        comment.save()
    return HttpResponseRedirect(reverse(post, args=(pk, )))
Пример #28
0
def blog_detail(request, pk):
    post = Post.objects.get(pk=pk)

    form = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(author=form.cleaned_data['author'],
                              body=form.cleaned_data['body'],
                              post=post)
            comment.save()

    comments = Comment.objects.filter(post=post)
    context = {"post": post, "comments": comments, "form": CommentForm()}
    return render(request, 'body_detail.html', context)
Пример #29
0
    def setUp(self):
        app = create_app('testing')
        self.context = app.test_request_context()
        self.context.push()
        self.client = app.test_client()
        self.runner = app.test_cli_runner()

        db.create_all()
        Role.init_role()

        admin_user = User(email='*****@*****.**',
                          name='Admin',
                          username='******')
        admin_user.set_password('123')
        admin_user.set_role()
        normal_user = User(email='*****@*****.**',
                           name='Normal User',
                           username='******')
        normal_user.set_password('123')
        unconfirmed_user = User(
            email='*****@*****.**',
            name='Unconfirmed',
            username='******',
        )
        unconfirmed_user.set_password('123')
        locked_user = User(email='*****@*****.**',
                           name='Locked User',
                           username='******',
                           locked=True)
        locked_user.set_password('123')
        locked_user.lock()

        blocked_user = User(email='*****@*****.**',
                            name='Blocked User',
                            username='******',
                            active=False)
        blocked_user.set_password('123')

        category = Category(name='test category')
        post = Post(title='test post', body='Test post', category=category)
        comment = Comment(body='test comment body',
                          post=post,
                          author=normal_user)
        db.session.add_all([
            admin_user, normal_user, unconfirmed_user, locked_user,
            blocked_user
        ])
        db.session.commit()
Пример #30
0
def blogPosts(request, post_id):
    post = Post.objects.get(pk=post_id)
    comment = Comment(post=post)
    if request.method == 'POST':  # If the form has been submitted...
        form = CommentForm(request.POST,
                           instance=comment)  # A form bound to the POST data
        if True:  # All validation rules pass
            comm_id = form.save().id
            return HttpResponseRedirect(
                '/blog/posts/%s#comment-%i' %
                (post_id, comm_id))  # Redirect after POST
    else:
        form = CommentForm()  # An unbound form

    context = {'post': post, 'form': form}
    return render(request, 'blog/blog_post.html', context)