示例#1
0
def Information(name):
    movie = Movie.query.filter_by(name=name).first()
    if request.method == 'GET':
        comment_list = Comment.query.filter_by(movie_id=movie.id).all()
        form = CommentForm()
        return render_template('MovieInfo.html', form=form, movie=movie, comment_list=comment_list)

    if request.method == "POST":
    #发表评论
        if current_user.is_authenticated:
            form = CommentForm()
            if form.validate_on_submit():
                comment = Comment(date=datetime.date.today(), title=form.title.data, content=form.content.data,
                                  rating=form.rating.data, user_id=current_user.id, movie_id=movie.id)
                db.session.add(comment)
                db.session.commit()
                flash("评论发表成功")
                print "success"
            comment_list = Comment.query.filter_by(movie_id=movie.id).all()
            #if comment_list and flag:
            render_template('MovieInfo.html', form=form, movie=movie, comment_list=comment_list)
            return redirect(url_for('Information', name=movie.name))
        else:
            flash("请登录后发表评论")
            return redirect(url_for('Information', name=movie.name))
示例#2
0
def comment(pid):
    form = CommentForm()
    post = Post.query.get(pid)
    post.visitors += 1
    db.session.add(post)
    if form.validate_on_submit():
        # 判断用户是否登录
        if current_user.is_authenticated:
            p = Post(content=form.content.data,
                     users_id=current_user.id,
                     rid=pid)
            db.session.add(p)
            form.content.data = ''
            flash('评论成功')

        else:
            flash('登录后才能发布评论哦')
            return redirect(url_for('users.login'))
    page = request.args.get('page', 1, type=int)
    pagination = Post.query.filter_by(rid=pid). \
        order_by(Post.timestamp.desc()).paginate(page, per_page=3, error_out=False)
    comments = pagination.items
    return render_template('common/comment.html',
                           form=form,
                           post=post,
                           pagination=pagination,
                           comments=comments)
示例#3
0
def Blog():
    form = PostForm()
    comment = Comment()
    form2 = CommentForm()
    if form.validate_on_submit():
        post = Post(body=form.post.data)
        db.session.add(post)
        db.session.commit()
        flash('You post your blog on the board!')
        return redirect(url_for('Blog'))
    if form2.validate_on_submit():
        newcomments = Comment(message=form2.message.data)
        db.session.add(newcomments)
        db.session.commit()
        flash('You added a comment!')
        return redirect(url_for('Blog'))

    posts = Post.query.all()
    comments = Comment.query.all()
    return render_template('Blog.html',
                           title="Share Your Piece",
                           form=form,
                           posts=posts,
                           commentForm=comment,
                           comments=comments,
                           form2=form2)
示例#4
0
def user_feed():
    if not current_user.is_authenticated:
        return redirect(url_for('github.login'))

    form = CommentForm()

    if form.validate_on_submit():
        user_id = current_user.id
        comment = Post(message=form.message.data, user_id=user_id)
        db.session.add(comment)
        db.session.commit()

    page = request.args.get('page', 1, type=int)
    comments = Post.query.order_by(Post.date_posted.desc()).paginate(
        page, app.config['POSTS_PER_PAGE'], False)

    next_url = url_for('user_feed', page=comments.next_num) \
        if comments.has_next else None

    prev_url = url_for('user_feed', page=comments.prev_num) \
        if comments.has_prev else None

    return render_template('user_feed.html',
                           form=form,
                           comments=comments.items,
                           next_url=next_url,
                           prev_url=prev_url,
                           current_user_id=current_user.id)
示例#5
0
def post(id):
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body=form.comment.data,
                          post=post,
                          author=current_user)
        db.session.add(comment)
        db.session.commit()
        flash('Your comment has been added.')
        return redirect(url_for('post', id=post.id))
    page = request.args.get('page', 1, type=int)
    comments = post.comments_for_post().paginate(page,
                                                 app.config['POSTS_PER_PAGE'],
                                                 False)
    next_url = url_for('post', page=comments.next_num) \
        if comments.has_next else None
    prev_url = url_for('post', page=comments.prev_num) \
        if comments.has_prev else None
    return render_template('post.html',
                           post=post,
                           form=form,
                           comments=comments.items,
                           next_url=next_url,
                           prev_url=prev_url)
示例#6
0
def article(slug):
    # Get the current page
    post = Post.query.filter_by(slug=slug).first()

    # Handle comment form handling
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body=form.body.data, post=post, author=current_user)
        db.session.add(comment)
        db.session.commit()
        flash("You comment is now live")
        return redirect(url_for("article", slug=slug))

    # Handle pagination of comments
    page = request.args.get("page", 1, type=int)
    comments = post.comments.paginate(page, app.config["POSTS_PER_PAGE"],
                                      False)
    next_url = url_for("article", slug=slug, page=comments.next_num) \
    if comments.has_next else None
    prev_url = url_for("article", slug=slug, page=comments.prev_num) \
    if comments.has_prev else None

    # Wrap the content as HTML
    body = Markup(post.body)

    return render_template("article.html",
                           title=post.title,
                           body=body,
                           post=post,
                           comments=comments.items,
                           next_url=next_url,
                           prev_url=prev_url,
                           form=form)
示例#7
0
def post(post_id):
    """View function for post page"""

    # Form object: `Comment`
    form = CommentForm()
    # form.validate_on_submit() will be true and return the
    # data object to form instance from user enter,
    # when the HTTP request is POST
    if form.validate_on_submit():
        new_comment = Comment(id=str(uuid4()), name=form.name.data)
        new_comment.text = form.text.data
        new_comment.date = datetime.now()
        new_comment.post_id = post_id
        db.session.add(new_comment)
        db.session.commit()

    post = Post.query.get_or_404(post_id)
    tags = post.tags
    comments = post.comments.order_by(Comment.date.desc()).all()
    recent, top_tags = sidebar_data()

    return render_template('post.html',
                           post=post,
                           tags=tags,
                           comments=comments,
                           form=form,
                           recent=recent,
                           top_tags=top_tags)
示例#8
0
文件: routes.py 项目: zhayan/yanblog
def article(article_name):
    page = request.args.get('page', 1, type=int)
    article = Article.query.filter_by(article_name=article_name).first_or_404()
    category = article.category
    comments = Comment.query.filter_by(article_id=article.id).order_by(
        Comment.timestamp.desc()).paginate(page,
                                           app.config['COMMENTS_PER_PAGE'],
                                           False)
    next_url = url_for('article', article_name=article_name, page=comments.next_num) \
     if comments.has_next else None
    prev_url = url_for('article', article_name=article_name, page=comments.prev_num) \
     if comments.has_prev else None
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(article_id=article.id,
                          nickname=form.nickname.data,
                          email=form.email.data,
                          body=form.comment.data)
        db.session.add(comment)
        db.session.commit()
        return redirect(
            url_for('article', article_name=article.article_name) +
            '#comments')
    return render_template('article.html',
                           category=category,
                           article=article,
                           title='article',
                           form=form,
                           comments=comments.items,
                           next_url=next_url,
                           prev_url=prev_url)
示例#9
0
def post(post_id):
    form = CommentForm()

    if form.validate_on_submit():
        new_comment = Comment()
        new_comment.name = form.name.data
        new_comment.text = form.text.data
        new_comment.post_id = post_id
        new_comment.date = datetime.datetime.now()

        db.session.add(new_comment)
        db.session.commit()

    post = Post.query.get_or_404(post_id)
    tags = post.tags
    comments = post.comments.order_by(Comment.date.desc()).all()
    recent, top_tags = sidebar_data()

    return render_template('post.html',
                           post=post,
                           tags=tags,
                           comments=comments,
                           recent=recent,
                           top_tags=top_tags,
                           form=form)
示例#10
0
def show_post(postID):
    categories = PostCategory().query.all()
    post = Post().query.get(int(postID))
    if post.post_url is not None:
        article = post.post_url
    else:
        article = 'site/post.html'

    newsletter_form = NewsLetterForm()
    comments = Comment.query.filter_by(post_id=postID).all()
    ref = 'blog/post/' + str(postID)
    # comment adder
    commentform = CommentForm()
    if commentform.validate_on_submit():
        comment = Comment(comment=commentform.comment.data,
                          post_id=post.id,
                          user_id=current_user.id)
        db.session.add(comment)
        db.session.commit()
        flash(
            'Your comment has been successfully added and pending Administrators approval to get live on blog.'
        )
        return redirect(ref)
    try:
        return render_template('site/post.html',
                               title=post.heading,
                               post=post,
                               newsletter_form=newsletter_form,
                               commentform=commentform,
                               comments=comments,
                               ref=ref,
                               post_categories=categories)
    except:
        return file_not_found(404)
示例#11
0
def comments(post_id):
    post = Post.query.filter_by(id=post_id).first_or_404()
    form = CommentForm()
    form0 = SearchProfileForm()
    if form.validate_on_submit():
        comment = Comment(body=form.comment.data,
                          author=current_user,
                          post=post)
        db.session.add(comment)
        db.session.commit()
        flash('Your comment is now live!')
        return redirect(url_for('comments', post_id=post.id))

    page = request.args.get('page', 1, type=int)
    comments = Comment.query.order_by(Comment.timestamp.desc()).filter_by(
        post=post).paginate(page, app.config['COMMENTS_PER_PAGE'], False)

    next_url = url_for('comments', post_id=post.id, page=posts.next_num) \
        if comments.has_next else None
    prev_url = url_for('comments', post_id=post.id, page=posts.prev_num) \
        if comments.has_prev else None

    return render_template('comments_section.html',
                           title='Comments',
                           upvote=Upvote,
                           badge_colour=badge_colour,
                           form=form,
                           form0=form0,
                           post=post,
                           comments=comments.items)
示例#12
0
def teacher(teacherId):
    teacher = Teacher.query.filter_by(id=teacherId).first()

    if teacher is not None:
        # Checking if user has previously commented on this teacher.
        prevcomment = Comment.query.filter_by(user_id=current_user.id,
                                              teacher_id=teacherId).first()
        print(prevcomment)
        if prevcomment is None:
            form = CommentForm()
            if form.validate_on_submit():
                comment = Comment(teacher_id=teacherId,
                                  user_id=current_user.id,
                                  value=form.comment.data)
                db.session.add(comment)
                db.session.commit()
                flash('Successfully added comment!')
                comments = Comment.query.filter_by(teacher_id=teacherId).all()
                return redirect(url_for('teacher', teacherId=teacherId))
                # return render_template('teacher.html', teacher=teacher, comments=comments)

            comments = Comment.query.filter_by(teacher_id=teacherId).all()
            return render_template('teacher.html',
                                   teacher=teacher,
                                   form=form,
                                   comments=comments)
        comments = Comment.query.filter_by(teacher_id=teacherId).all()
        return render_template('teacher.html',
                               teacher=teacher,
                               comments=comments)
    flash('Invalid Teacher ID')

    return render_template(url_for('view_teachers'))
示例#13
0
def group_comments(id):
    # Get all comments for a given group
    method = request.method
    if method == 'GET':
        comments = []
        comments_from_group = Group.query.get(id).comments
        for comment in comments_from_group:
            comments.append({
                "comment": comment.to_dict()
            })
        return jsonify(comments if comments else '!')
        # return jsonify(comments)
    if method == 'POST':
      # Add a comment to a given group
        form = CommentForm()
        form['csrf_token'].data = request.cookies['csrf_token']
        comment = ''
        if form.validate_on_submit():
          # REPLACE WITH current_user.id
            comment = Comment(
                group_id=id,
                user_id=current_user.id,
                content=form.data['content'],
                photo_url=form.data['photo_url'],
            )
            db.session.add(comment)
            db.session.commit()
        return jsonify({'comment': comment.to_dict()} if comment else 'Invalid Operation')
def detail_view(rec_number):
    # создадим формы
    commentform = CommentForm()
    tagform = TagForm()
    # сохраним начала ключей данного оюъявления в редис
    tag_key = f'{rec_number}:tags'
    comment_key = f'{rec_number}:comments:'
    # выгребаем из кэша простые словари, без вложенностей
    bul = fish_out_of_cache_simple(r, rec_number)
    # если есть тэги, запрашиваем и их, но т.к. они хранятся в виде сета, то для них используется другая команда
    if r.scard(tag_key) > 0:
        bul['tags'] = [x.decode("utf-8") for x in r.smembers(tag_key)]

    # Выбираем из кэша комменты. Перебираем все по очереди, используя начало ключа и счетчик
    # когда оба запроса на предполагаемый контент вернут ничего, останавливаемся
    bul['comments'] = []
    comment_count = 0
    while True:
        author = r.get(f'{comment_key}{comment_count}:author')
        content = r.get(f'{comment_key}{comment_count}:content')
        if not (author and content):
            break
        comment_count += 1
        bul['comments'].append({
            'author': author.decode("utf-8"),
            'content': content.decode("utf-8")
        })

    # если с формы пришли тэги, превращаем их в массив и закидываем в редис
    # если после этого окажется, что сэт увеличился, переписываем в сэт в бд
    if tagform.validate_on_submit():
        new_tags = make_tags(tagform.tags.data)
        r.sadd(tag_key, *new_tags)
        if r.scard(tag_key) > len(bul['tags']):
            col.update_one({"_id": ObjectId(rec_number)}, {
                "$set": {
                    "tags": [x.decode("utf-8") for x in r.smembers(tag_key)]
                }
            })
        return redirect(url_for('detail_view', rec_number=rec_number))

    # берем новый коммент с формы и записываем и в бд и в кэш
    if commentform.validate_on_submit():
        new_comment = {
            "author": commentform.author.data,
            "content": commentform.content.data,
        }
        col.update_one({"_id": ObjectId(rec_number)},
                       {"$push": {
                           "comments": new_comment
                       }})
        r.set(f'{comment_key}{comment_count}:author', new_comment['author'])
        r.set(f'{comment_key}{comment_count}:content', new_comment['content'])
        return redirect(url_for('detail_view', rec_number=rec_number))
    return render_template('bul_detail.html',
                           title='Bulletin',
                           bul=bul,
                           cmform=commentform,
                           tgform=tagform)
示例#15
0
def comment(post_id):
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(comment=form.comment.data)
        db.session.add(comment)
        db.session.commit()
    flash('your comment has been added', 'success')
    return render_template('comment.html')
示例#16
0
def comment(post_id):
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(content=form.content.data, post_id=post_id, author=current_user.username)
        db.session.add(comment)
        db.session.commit()
        flash('Your comment has been added!', 'success')
        return redirect(url_for('post', post_id=post_id))
    return render_template('comment.html', form=form)
示例#17
0
def comfunction():
    comment = Comments.query.filter().all()
    form = CommentForm()
    if form.validate_on_submit():
        com = Comments(content=form.content.data)
        db.session.add(com)
        db.session.commit()
        flash('Congratulations, you have issued!')
        return redirect(url_for('index'))
    return render_template('commentArea.html', form=form, comment=comment)
示例#18
0
def Makecomment(postid):
    commentform=CommentForm()
    if request.method == "POST" and commentform.validate_on_submit():
        profileid=session.get('ThisProfileid')
        commentbody=commentform.Comments.data
        postid
        print(MakeComment(profileid,commentbody,postid))


    return redirect(url_for('PandC'))
示例#19
0
def show_speaker(speaker_id):
    speaker = Speaker.query.filter_by(id=speaker_id).first_or_404()
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(author=current_user, comment=form.comment.data, speaker=speaker)
        db.session.add(comment)
        db.session.commit()
        return redirect(url_for('show_speaker', speaker_id=speaker_id))

    return render_template('show_speaker.html', title=speaker.name, speaker=speaker, form=form)
示例#20
0
def show_event(event_id):
    event = Event.query.filter_by(id=event_id).first_or_404()
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(author=current_user, comment=form.comment.data, event=event)
        db.session.add(comment)
        db.session.commit()
        return redirect(url_for('show_event', event_id=event_id))

    return render_template('show_event.html', title=event.topic, event=event, form=form)
示例#21
0
def comment_post(post_id):
    post = Post.query.get_or_404(post_id)
    form = CommentForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            comment = Comment(body=form.body.data, post_id=post.id)
            db.session.add(comment)
            db.session.commit()
            return redirect(url_for('index', post_id=post.id))
    return redirect(request.referrer)
示例#22
0
def edit(comment_id):
    comment = Comment.query.get_or_404(comment_id)
    #comment.permissions.edit.test(403)
    form = CommentForm(obj=comment)
    if form.validate_on_submit():
        form.populate_obj(comment)
        comment.save()
        flash(u"你的评论已更新", "successfully")
        return redirect(comment.url)
    return render_template("comment/edit.html", comment=comment, form=form)
示例#23
0
def comments():
    comments = Post.query.all()
    form = CommentForm()
    if form.validate_on_submit():
        post = Post(content=form.content.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Comment created successfully.', 'success')
        return redirect(url_for('comments'))
    return render_template("comments.html", form=form, comments=comments)
示例#24
0
def show_bug(bug_id):
    if not session.get('username'):
        return redirect(url_for('index'))
    if not bug_id:
        redirect(url_for('index'))
    bug = Bug.query.get_or_404(bug_id)
    issue_type = bug.issue_type.issue_type
    status = bug.status.status
    priority = bug.priority.priority
    today = datetime.utcnow()
    project = bug.project
    components = bug.component
    assignee = bug.assignee.user
    reporter = bug.reporter.user
    creator = bug.creator
    form = CommentForm()
    delete_form = DeleteBugForm()
    comments = bug.comments
    if form.validate_on_submit():
        Comment(body=form.body.data,
                bug_id=bug_id,
                user=User.query.filter_by(
                    username=session.get('username')).first()).save()
        flash('Your comment has been published.', 'success')
        return redirect(url_for('show_bug', bug_id=bug_id))
    if request.method == 'POST' and request.form.get('delete_comment'):
        comment_id = int(request.form.get('delete_comment'))
        app.logger.info(f"Deleting Comment {comment_id}")
        comment = Comment.query.get(comment_id)
        if comment:
            db.session.delete(comment)
            app.logger.info(f"Comment {comment_id} Deleted.")
            flash(f"Comment {comment_id} has been deleted.", "success")
            db.session.commit()
    if delete_form.is_submitted() and request.form.get('delete'):
        delete_bug(delete_form, bug)
        return redirect(url_for("bugs"))
    return render_template("show_bug.html",
                           form=form,
                           comments=comments,
                           project=project,
                           assignee=assignee,
                           creator=creator,
                           reporter=reporter,
                           bug=bug,
                           issue_type=issue_type,
                           status=status,
                           priority=priority,
                           title="Bugs",
                           User=User,
                           bugs=True,
                           today=today,
                           components=components,
                           show_bugs_flag=True,
                           delete_form=delete_form)
示例#25
0
 def add_comment(post_id):
     post = Post.query.get(post_id)
     comment_form = CommentForm()
     if comment_form.validate_on_submit():
         comment = Comment(content=comment_form.content.data,
                           user_id=current_user.id,
                           post_id=post_id)
         db.session.add(comment)
         db.session.commit()
         url = url_for('show_post', post_id=post.id)
         return redirect(url)
示例#26
0
def edit_comment(commentId):
    current_comment = Comment.query.get(int(commentId))
    user_id = current_user.get_id()
    form = CommentForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        current_comment.body = form.data['body']
        db.session.add(current_comment)
        db.session.commit()
        return current_comment.to_dict()
    return {'error': 'could not post'}
示例#27
0
def new_comment(post_id):
    form = CommentForm()
    if form.validate_on_submit():
        user = User.query.filter_by(
            username=current_user.username).first_or_404()
        comment = Comment(body=form.body.data, user_id=user.id, post_id=post_id)
        db.session.add(comment)
        db.session.commit()
        flash('Your new comment has been saved.')
        # go to new comment when done
        return redirect(url_for('post', post_id=post_id))
    return render_template('edit_comment.html', title="New Comment", form=form)
示例#28
0
def post_comment(postId):
    user_id = current_user.get_id()
    form = CommentForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        new_comment = Comment(body=form.data['body'],
                              userId=user_id,
                              postId=postId)
        db.session.add(new_comment)
        db.session.commit()
        return {new_comment.to_dict()['id']: new_comment.to_dict()}
    return {'error': 'could not post'}
示例#29
0
def new_comment(pollId):
  errors=["An error occurred while creating a comment."]
  form = CommentForm()
  form['csrf_token'].data = request.cookies['csrf_token']

  if form.validate_on_submit():
    new_comment = Comment(answer_text=form.data['answer_text'], poll_id=int(pollId), user_id=current_user.get_id())
    db.session.add(new_comment)
    db.session.commit()
    return { new_comment.get_id(): new_comment.to_dict() }

  return { "errors": errors }
示例#30
0
def article(id):
	a = Article.query.get(id)
	form = CommentForm()

	if form.validate_on_submit():
		c = Comment(user_id = 1, message = form.message.data,article = a )
		

		c.save()

	comments = Comment.query.filter_by(article_id = id)
	return render_template('article.html', article = a, comments = comments, form=form)
示例#31
0
def edit(comment_id):
    comment = Comment.query.get_or_404(comment_id)
    #comment.permissions.edit.test(403)
    form = CommentForm(obj=comment)
    if form.validate_on_submit():
        form.populate_obj(comment)
        comment.save()
        flash(u"你的评论已更新", "successfully")
        return redirect(comment.url)
    return render_template("comment/edit.html",
                           comment=comment,
                           form=form)
示例#32
0
def detail(slug):
    """View details of post with specified slug."""
    post = Post.query.slug_or_404(slug)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(
            form.name.data,
            form.body.data,
            request.remote_addr,  # ip
            post.id,
            form.reply_id.data or None
        )
        db.session.add(comment)
        db.session.commit()
    return render_template('detail.html', post=post, form=form)
示例#33
0
文件: post.py 项目: yxm0513/7topdig
def add_comment(post_id, parent_id=None):
    post = Post.query.get_or_404(post_id)
    post.permissions.view.test(403)
    parent = Comment.query.get_or_404(parent_id) if parent_id else None
    
    #user = User.query.first()
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(post=post,
                          parent=parent,
                          author=current_user)
        form.populate_obj(comment)
        comment.save()
        post.num_comments += 1
        post.save()

        save_action(u"评论了条目 " + u'"' + post.title + u'"' )

        #comment_added.send()
        flash(u"谢谢你的评论", "successfully")
        author = parent.author if parent else post.author

        if author.email_alerts and author.id != current_user.id:
            if setting.MAIL_ENABLE:
                subject = u"有人回复了你的评论" if parent else \
                          u"有人给你的提交添加了评论"
                template = "emails/comment_replied.html" if parent else \
                           "emails/post_commented.html"
                body = render_template(template,
                                       author=author,
                                       post=post,
                                       parent=parent,
                                       comment=comment)
                mail.send_message(subject=subject,
                                  body=body,
                                  recipients=[post.author.email])
                flash(u"谢谢,你的邮件已发出", "successfully")
            else:
                flash(u"邮件服务器未开启,请联系管理员", "error")
        return redirect(comment.url)
    return render_template("post/add_comment.html",
                           parent=parent,
                           post=post,
                           form=form)
示例#34
0
def comment_create(article_id):
    form = CommentForm()
    if request.method == 'GET':
        return render_template('comment/create.html', form=form)
    elif request.method == 'POST':
        if form.validate_on_submit():
            comment = Comment(
                author=form.author.data,
                email=form.email.data,
                content=form.content.data,
                password=form.password.data,
                article=Article.query.get(article_id)
            )

            db.session.add(comment)
            db.session.commit()

            flash(u'게시글을 작성하였습니다.', 'success')
            return redirect(url_for('article_detail', id=article_id))
        return render_template('comment/create.html', form=form)