Esempio n. 1
0
def teamProfile(teamId):
	if current_user.team:
		if int(teamId) == int(current_user.team_id):
			return redirect(url_for('team_page'))
	form = CommentForm()
	team = db.session.query(Team).filter(Team.id == teamId).first()
	comments = db.session.query(Comment).filter(Comment.idea_id == team.idea.id).all()

	if not team:
		flash('Team '+teamId+' not found.', 'error')
		return redirect(url_for('home'))
	else:
		if form.validate_on_submit():
			comment = Comment()
			comment.content = form.comment.data
			team.idea.comment.append(comment)
			current_user.comment.append(comment)
			db.session.add(comment)

			for member in comment.idea.team.members:
				notif = PersonalNotification()
				notif.content = current_user.username + " commented on your team's idea."
				member.notification.append(notif)

			db.session.commit()
			return render_template('team_view.html', form=form, team=team, comments=comments)

		return render_template('team_view.html', form=form, team=team, comments=comments)
def comment_form():

    form = CommentForm()

    try:
        if 'user_id' in session:
            _user = users_coll.find_one({"_id": ObjectId(session['user_id'])})

        if session['user_id'] == "5e52eae5426c4d0b8d01cbc2":  # admin Object ID

            # if form is submitted comments are added to DB
            if form.validate_on_submit():
                comments = mongo.db.comments
                comments.insert_one({
                    # 'book_title': books,
                    'book_hook': request.form.get('book_hook'),
                    'user_comments': request.form.get('user_comments'),
                    'added_by': _user
                        # {'_id': ObjectId(session['user_id'])}
                        })
                flash('Your Note Has Been Added!')
                return redirect(url_for('all_comments', user=_user, form=form))
            return render_template('comment_form.html', user=_user, form=form, books=mongo.db.books.find())

        else:
            flash("Restricted Area - Access Denied!")
            return render_template('index.html')

    except:
        if 'user_id' not in session:
            flash("Restricted Area - Access Denied!")
            return render_template('index.html')
Esempio n. 3
0
def post(id):
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body=form.body.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        flash('Your comment has been published')
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() -1)//\
            current_app.config['COMMENTS_PER_PAGE'] + 1
    pagination = post.comments.filter_by(parrent_id=None).order_by(
        Comment.timestamp.asc()).paginate(
            page,
            per_page=current_app.config['COMMENTS_PER_PAGE'],
            error_out=False)
    comments = pagination.items
    return render_template('post.html',
                           posts=[post],
                           post_form=form,
                           comments=comments,
                           pagination=pagination,
                           Comment=Comment)
Esempio n. 4
0
def get_aritle(number):
    article = get_aritle_by_number(number)
    if article is None or not article.is_public:
        return render_template('404.html'), 404

    form = CommentForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            try:
                month_number = int(form.checker.data)
            except ValueError:
                month_number = 0
            if month_number != datetime.date.today().month:
                form.checker.errors = ["Sorry, but please prove you are a human."]
                form.checker.data = ""
            else:
                comment = Comment(
                    article_number=number,
                    author=form.author.data,
                    comment=form.comment.data,
                )
                comment.save()
                return redirect(article.get_absolute_url())

    comments = get_comments(number)
    return render_template(
        'article.html',
        article=article,
        form=form,
        comments=comments,
    )
Esempio n. 5
0
def thisdiary(friend_diary):
    # friendID,diarychoose=friend_diary
    info = friend_diary.split(",")
    diarychoose = info[1]

    cur_user = info[0]
    form = CommentForm()
    diary_show = Record(cur_user)
    diary = diary_show.display_single(diarychoose)
    diary = diary[0]
    comment_show = Comment()
    comments = comment_show.show_group_dialog(diarychoose)
    if form.validate_on_submit():
        comment = request.form.get('comment', None)
        time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        record_id = diarychoose
        comment_new = Comment()
        comment_new.create_dialog(record_id, current_user.user_email, time,
                                  comment)
        friend_diary = cur_user + "," + diarychoose
        return redirect(
            request.args.get('next')
            or url_for('thisdiary', friend_diary=friend_diary))
    return render_template('thisdiary.html',
                           title="Sign In",
                           form=form,
                           diary=diary,
                           comments=comments,
                           user_info_global=user_info_global)
Esempio n. 6
0
def add_exercise_comment(category_id, exercise_id):
    """Handle comment for an exercise."""

    # This is a private endpoint, check if user is logged in
    if "username" not in session:
        raise Unauthorized()

    form = CommentForm()

    username = session['username']

    if form.validate_on_submit():
        user = User.query.filter_by(username=username).first()

        content = form.content.data

        exercise_comment = ExerciseComment(exercise_id=exercise_id,
                                           user_id=user.id,
                                           content=content)

        db.session.add(exercise_comment)

        db.session.commit()

    return redirect(f"/exercises/{category_id}/{exercise_id}")
Esempio n. 7
0
def blog(id):
    '''每篇博客的单独页面,便于分享'''
    blog = Blog.query.get_or_404(id)
    # 页面提供评论输入框
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body=form.body.data, blog=blog, author=current_user)
        db.session.add(comment)
        db.session.commit()
        flash('评论成功。', 'success')
        return redirect(url_for('.blog', id=id))
    page = request.args.get('page', default=1, type=int)
    pagination = blog.comments.order_by(Comment.time_stamp.desc()).paginate(
        page,
        per_page=current_app.config['COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    # hidebloglink 在博客页面中隐藏博客单独页面的链接
    # noblank 在博客页面中点击编辑按钮不在新标签页中打开
    return render_template('blog.html',
                           blogs=[blog],
                           hidebloglink=True,
                           noblank=True,
                           form=form,
                           pagination=pagination,
                           comments=comments,
                           Permission=Permission)
Esempio n. 8
0
def edit_event(event_id):
    form = CommentForm()
    entry = Comment.query.filter_by(id = event_id).first_or_404()
    print entry.text2
    if form.validate_on_submit():
        comment = Comment(
            form.text.data,
            form.text2.data,
            form.longitude.data,
            form.latitude.data,
            form.date.data,
            datetime.now(),
            current_user.get_id()
        )
        entry.text = form.text.data 
        entry.text2 = form.text2.data
        entry.longitude = form.longitude.data
        entry.latitude = form.latitude.data
        entry.date = form.date.data
        db.session.commit()
        return redirect(url_for('my_events'))
    else:
        form = CommentForm(obj=entry)
        form.populate_obj(entry)
    return render_template('edit_event.html', entry=entry, form=form)
Esempio n. 9
0
def trade_detail(goodId):
    post = Post.query.get_or_404(goodId)
    form = CommentForm()
    if form.validate_on_submit():
        if current_user.is_anonymous:
            flash(u'请登录后再尝试评论帖子')
            return redirect(url_for('auth.passport'))
        else:
            comment = Comment(body=form.body.data, post=post,
            author = current_user._get_current_object())
            db.session.add(comment)
            db.session.commit()
            flash(u'你的评论已提交.')
            return redirect(url_for('.trade_detail', goodId=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() - 1) // \
            current_app.config['JXNUGO_COMMENTS_PER_PAGE'] + 1
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page, per_page=current_app.config['JXNUGO_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    author = current_user._get_current_object()
    return render_template('trade/trade_detail.html', post=post, form=form,
                           comments=comments, pagination=pagination,user=author)
Esempio n. 10
0
def show_post(post_id):
    requested_post = BlogPost.query.get(post_id)
    form = CommentForm()
    for comment in requested_post.comments:
        print(comment.text)
        print(comment.author.name)
    if form.validate_on_submit():
        if not current_user.is_authenticated:
            flash("You need to login or register to comment.")
            return redirect(url_for("login"))

        new_comment = Comment(
            text=form.text.data,
            author=current_user,
            post=requested_post
            # you could also directly set the foreign key id's instead of the two lines above:
            # author_id=current_user.id,
            # post_id=requested_post.id
        )
        db.session.add(new_comment)
        db.session.commit()
        return redirect(url_for("get_all_posts", current_user=current_user))

    return render_template("post.html",
                           post=requested_post,
                           current_user=current_user,
                           form=form)
Esempio n. 11
0
def show_post(post_id):
    # don't show the about post page
    if post_id == 1:
        return abort(404)
    form = CommentForm()
    requested_post = BlogPost.query.get_or_404(post_id)
    if not check_admin():

        # don't show the hidden post
        if requested_post.hidden:
            return abort(404)
        if not requested_post.views:
            requested_post.views = 0

        # increment the post views
        requested_post.views += 1
        db.session.commit()

    # if user leave a comment
    if form.validate_on_submit():
        if current_user.is_authenticated:
            comment = Comment(
                author_id=current_user.id,
                post_id=post_id,
                text=form.comment_text.data
            )
            db.session.add(comment)
            db.session.commit()
            return redirect(url_for("show_post", post_id=post_id))

        # redirect to log in page if not authenticated
        flash("You need to log in first before leaving any comments.")
        return redirect(url_for("login"))

    return render_template("post.html", post=requested_post, form=form, logged_in=current_user.is_authenticated, title=f"{requested_post.title} Arsa Izdihar Islam's Blog")
Esempio n. 12
0
def show_post(post_id):
    requested_post = BlogPost.query.get(post_id)
    form = CommentForm()
    if form.validate_on_submit():
        # Ensure poster is logged in
        if not current_user.is_authenticated:
            flash("You need to login or register to comment")
            return redirect(url_for('login'))

        # save to the database
        post_text = form.body.data
        user_id = current_user.id
        post_id = post_id
        comment = Comment(post_id=post_id, user_id=user_id, text=post_text)
        db.session.add(comment)
        db.session.commit()

    # Build up comments and send to page

    comments = db.session.query('text', 'email', 'name')\
        .from_statement(text(f"SELECT C.TEXT as text, "
                             f"U.EMAIL as email, "
                             f"U.NAME as name "
                             f"FROM COMMENTS C, USERS U "
                             f"WHERE C.USER_ID=U.ID "
                             f"AND C.POST_ID={post_id}"))\
        .all()
    # comments.reverse()  # use if want most recent comments at the top as comments is list

    return render_template("post.html",
                           post=requested_post,
                           form=form,
                           comments=comments)
Esempio n. 13
0
def pow(val):
    form = CommentForm()
    deleteform = DeleteForm()
    if form.validate_on_submit() and form.comment.data:
        comment = models.Comment(comment=form.comment.data, userid=current_user.id, powid=val)
        db.session.add(comment)
        db.session.commit()
    # elif deleteform.validate_on_submit():
    #    return redirect('/about')
    comments = models.Comment.query.filter(models.Comment.powid == val).all()
    pow = models.Prisoner.query.filter_by(id=val).first_or_404()
    surname = pow.surname
    capture = pow.Capture
    firstnames = pow.first_names
    if firstnames == None:
        firstnames = pow.initial
    count = models.Prisoner.query.filter(models.Prisoner.capture == capture.id).count()
    # grammar for prisoner page
    if isinstance(capture.date, str) == True:
        inor = "on"
        sent = "on this date"
    else:
        inor = "in"
        sent = "at this location"
    return render_template("prisoner.html", val=val, prisoner=pow, first_names=firstnames, inor=inor, sent=sent,
                           count=count, form=form, comments=comments)
Esempio n. 14
0
def show_post(post_id):
    '''
    Read a Post by Id.

    Allow the user to Comment if logged in.
    '''
    form = CommentForm()
    # find the requested post
    requested_post = mongo.db.blog_posts.find_one({"_id": ObjectId(post_id)})
    requested_post_comments = mongo.db.blog_comments.find(
        {"parent_post": ObjectId(post_id)})

    # commenting on a post
    if form.validate_on_submit():
        if not session["user"]:
            flash("You need to login or register to comment.")
            return redirect(url_for("login"))

        new_comment = {
            "text": form.comment_text.data,
            "comment_author": session["user"],
            "parent_post": ObjectId(post_id)
        }

        mongo.db.blog_comments.insert_one(new_comment)
    return render_template("post.html",
                           post=requested_post,
                           comments=requested_post_comments,
                           form=form)
def show_post(post_id):
    gravatar = Gravatar(app,
                        size=100,
                        rating='g',
                        default='retro',
                        force_default=False,
                        force_lower=False,
                        use_ssl=False,
                        base_url=None)

    comment_form = CommentForm()
    comments = Comment.query.all()
    requested_post = BlogPost.query.get(post_id)
    if comment_form.validate_on_submit():
        if not current_user.is_authenticated:
            flash("You need to login or register for making comment")
            return redirect(url_for('login'))
        new_comment = Comment(
            text=comment_form.body.data,
            author_id=current_user.id,
            post_id=post_id,
        )
        db.session.add(new_comment)
        db.session.commit()
        return redirect(url_for('show_post', post_id=post_id))
    return render_template("post.html", post=requested_post, logged_in=current_user.is_authenticated, form=comment_form,
                           all_comments=comments, current_user=current_user)
Esempio n. 16
0
def timeline():
    form = CommentForm(request.form)
    follow_form = Follow(request.form)
    unfollow_form = Unfollow(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            #get comment posted
            comment = form.comment.raw_data[0]
            #get post uuid
            parentID = form.parentID.raw_data[0]
            #get post author (will later be changed to current_user)
            author = form.author.raw_data[0]
            #loop through posts until we find the post with a matching uuid
            if 'comment' in request.form:
                for post in posts:
                    if post['uuid'] == parentID:
                        comment_data = {'author': author, 'comment': comment}
                        #update list of comments for that post
                        post['comments'].append(comment_data)
                        break
                with open('app/static/posts.json', 'w') as all_posts:
                    dump(posts, all_posts, indent=4, sort_keys=True)
            return redirect(url_for('timeline'))
        if 'follow_user' in request.form:
            follow(session.get('username'), request.form.get('follow_user'))
        if 'unfollow_user' in request.form:
            unfollow(session.get('username'),
                     request.form.get('unfollow_user'))
    return render_template('timeline.html',
                           posts=posts,
                           form=form,
                           username=session.get('username'),
                           accounts=accounts,
                           follow_form=follow_form,
                           unfollow_form=unfollow_form)
Esempio n. 17
0
def add_comment():
    """
    Add a comment to the database
    """
    check_admin()
    add_comment = True
    form = CommentForm()
    if form.validate_on_submit():
        comments = mongo.db.comments
        try:
            # add comment to the database
            comments.insert({
                'comment_videoname': form.comment_videoname.data,
                'comment_nickname': form.comment_nickname.data,
                'reply_nickname': form.reply_nickname.data,
                'comment_content': form.comment_content.data,
                'comment_gender': form.comment_gender.data,
                'comment_address': form.comment_address.data,
                'comment_time': form.comment_time.data
            })
            flash(u'您已经成功添加一个评论信息')
        except:
            # in case comment name already exists
            flash(u'错误: 该评论信息已存在')

        # redirect to comment page
        return redirect(url_for('admin.list_comments'))

    # load comment template
    return render_template('admin/comments/comment.html',
                           action="Add",
                           add_comment=add_comment,
                           form=form,
                           title=u"添加评论信息")
Esempio n. 18
0
def get_post(index):

    post_to_get = BlogPost.query.get(int(index))

    comment_list = Comment.query.all()
    comment_form = CommentForm()

    if comment_form.validate_on_submit():

        if current_user.is_authenticated:

            new_comment = Comment(text=comment_form.body.data,
                                  author_id=current_user.id,
                                  post_id=post_to_get.id)

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

            return redirect(url_for("home"))
        else:
            flash("You need to login or register to add comments.")
            return redirect(url_for("login"))

    return render_template("post.html",
                           post=post_to_get,
                           user=current_user,
                           form=comment_form,
                           comments=comment_list)
Esempio n. 19
0
def show_post(post_id):
    comment_form = CommentForm()
    requested_post = BlogPost.query.get(post_id)

    if comment_form.validate_on_submit():
        if not current_user.is_authenticated:
            flash("First you need to login or register to make any comments.")
            return redirect(url_for("login"))

        new_comment = Comment(text=comment_form.comment.data,
                              comment_author=current_user,
                              comment_date=dt.now().strftime("%B %d,%Y"),
                              comment_time=dt.now().strftime("%I:%M %p"),
                              parent_post=requested_post)
        db.session.add(new_comment)
        db.session.commit()

        # Clear comment form after it is submitted - Two Ways to do it:
        # Method 1-
        return redirect(url_for("show_post", post_id=post_id))

    # Method 2-
    # comment_form.comment.data = ""

    return render_template("post.html",
                           post=requested_post,
                           current_user=current_user,
                           form=comment_form,
                           year=CURRENT_YEAR)
Esempio n. 20
0
File: views.py Progetto: Morgl/charo
def show_post(url):
	query = {'url': url} if 'logged_in' in session else {'url': url, 'published': 'true'}
	post = mongo.db.posts.find_one_or_404(query)
	post['content'] = Markup(markdown.markdown(post['content']))
	form = CommentForm()
	error = ""
	if request.method == 'POST':
		if form.validate_on_submit():
			is_admin = True if 'logged_in' in session else False
			comment = {
				'_id': len(post['comments'])+1,
				'username': form.username.data,
				'email': form.email.data,
				'message': form.message.data,
				'date': strftime('%d/%m/%Y - %H:%M'),
				'admin': is_admin
			}
			mongo.db.posts.update(
				{ 'url': url },
				{ '$push': { 'comments': comment } }
			)
			return redirect(url_for('show_post', url=url))
		else:
			error = "Invalid comment form!"
	return render_template('post.html', post=post, form=form, error=error, session=session)
Esempio n. 21
0
def comment_new():
  form = CommentForm()    # flask-wtf automatically looks into request
  if form.validate_on_submit():
    comment = Comment(form.email.data, form.body.data)
    db.session.add(comment)
    db.session.commit()
    return redirect('/success')
  return render_template('submit.html', form=form)
Esempio n. 22
0
def edit_comment(name):
    """
    Edit a comment
    """
    check_admin()
    add_comment = False
    comment = mongo.db.comments.find({"comment_nickname": name})
    comments = mongo.db.comments
    edit_comment = {
        'comment_videoname': u"待赋值",
        'comment_nickname': u"待赋值",
        'reply_nickname': u"待赋值",
        'comment_content': u"待赋值",
        'comment_gender': u"待赋值",
        'comment_address': u"待赋值",
        'comment_time': u"待赋值"
    }
    commentarray = CommentsArray(comment_videoname=u"待赋值",
                                 comment_nickname=u"待赋值",
                                 reply_nickname=u"待赋值",
                                 comment_content=u"待赋值",
                                 comment_gender=u"待赋值",
                                 comment_address=u"待赋值",
                                 comment_time=u"待赋值")
    for s in comment:
        commentarray.comment_videoname = s['comment_videoname']
        commentarray.comment_nickname = s['comment_nickname']
        commentarray.reply_nickname = s['reply_nickname']
        commentarray.comment_content = s['comment_content']
        commentarray.comment_gender = s['comment_gender']
        commentarray.comment_address = s['comment_address']
        commentarray.comment_time = s['comment_time']

    form = CommentForm(obj=commentarray)
    comments.remove({'comment_nickname': name})
    if form.validate_on_submit():
        edit_comment['comment_videoname'] = form.comment_videoname.data
        edit_comment['comment_nickname'] = form.comment_nickname.data
        edit_comment['reply_nickname'] = form.reply_nickname.data
        edit_comment['comment_content'] = form.comment_content.data
        edit_comment['comment_gender'] = form.comment_gender.data
        edit_comment['comment_address'] = form.comment_address.data
        edit_comment['comment_time'] = form.comment_time.data
        comments.insert(edit_comment)
        flash(u'您已经成功修改评论信息')

        # redirect to the comment page
        return redirect(url_for('admin.list_comments'))
    for s in comment:
        form.comment_videoname.data = s['comment_videoname']
        form.comment_nickname.data = s['comment_nickname']

    return render_template('admin/comments/comment.html',
                           action="Edit",
                           add_comment=add_comment,
                           form=form,
                           comment=comment,
                           title=u"修改评论信息")
Esempio n. 23
0
def add_review():
    form = CommentForm()
    if form.validate_on_submit():
        current_date = date.today().strftime('%d/%m/%Y')
        name = request.form['name']
        comment = request.form['comment']
        write_csv_file(comments_file_path, [name, comment, current_date])
        return redirect(url_for('show_reviews'))
    return show_reviews(form)
Esempio n. 24
0
def view_post(id):
    """ Render a single Post"""
    post = Post.query.get(id)
    if post.status != 1:
        post = None
    form = CommentForm()
    if form.validate_on_submit():
        flash('Post comment added successfully!')
    return render_template("view_post.html", post=post, form=form)
Esempio n. 25
0
def exchanger(r):
    ex = db.session.query(models.Exchangers).filter_by(id=r).first()
    if not ex:
        abort(404)
    ex_data = [ex.name, ex.country, ex.description, ex.comments, ex.positives, ex.complains, ex.link, ex.id, ex.ownerId,
               ex.image, ex.dateOfCreation]

    badges = []
    if ex.badges:
        badges = ex.badges.split(',')

    form = CommentForm()
    form1 = EditForm()

    comments = db.session.query(models.Comment).filter(models.Comment.exchangerId == r)
    comments = comments[::-1]

    recent = comments[:5]

    if form.validate_on_submit():
        if len(form.review.data) > 5:
            if current_user.id == ex.ownerId:
                new_comment = models.Comment(review=str(form.review.data), type=str(form.type.data),
                                         userId=current_user.id, userName=current_user.name, exchangerId=r, byAdmin=1)
            else:
                new_comment = models.Comment(review=str(form.review.data), type=str(form.type.data),
                                             userId=current_user.id, userName=current_user.name, exchangerId=r, byAdmin=0)

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

            if current_user.id != ex.ownerId:
                if form.type.data == 'Positive':
                    ex.positives = ex.positives + 1
                elif form.type.data == 'Complain':
                    ex.complains = ex.complains + 1
                else:
                    ex.comments = ex.comments + 1

            db.session.commit()
            return redirect('/exchanger/{}'.format(r))

    ex = db.session.query(models.Exchangers).filter_by(id=r).first()
    if form1.validate_on_submit():
        if form1.name.data:
            ex.name = form1.name.data
        if form1.url.data:
            ex.link = form1.url.data
        if form1.description.data:
            ex.description = form1.description.data
        # if form1.picURL.data:
        #     ex.image = form1.picURL.data

        db.session.commit()
        return redirect('/exchanger/{}'.format(r))

    return render_template('exchanger.html', ex_data=ex_data, form=form, comments=comments, recent=recent, form1=form1, badges=badges)
Esempio n. 26
0
def add_comment(url):
    form = CommentForm()
    if form.validate_on_submit():
        author = form.author.data
        email = form.email.data
        comment = form.comment.data
        db.add_comment(url, author, email, comment)
        return redirect(url_for('show_post', url=url))
    return show_post(url=url, form=form)
Esempio n. 27
0
def detail(postid):
	post = Post.query.filter_by(id = postid).first()
	form = CommentForm()
	if form.validate_on_submit():
		comment = Comment(content = form.content.data,post_id = postid,user_id = 2,timestamp = datetime.now())
		comment.saveComment()
		redirectURL = url_for('.detail',postid = postid)
		return redirect(redirectURL + '#respond')
	return render_template('detail.html',post = post,form = form),200
Esempio n. 28
0
File: refer.py Progetto: kkris/refer
def add_comment(url):
    form = CommentForm()
    if form.validate_on_submit():
        author = form.author.data
        email = form.email.data
        comment = form.comment.data
        db.add_comment(url, author, email, comment)
        return redirect(url_for('show_post', url=url))
    return show_post(url=url, form=form)
Esempio n. 29
0
def add_comment(post_id):
    comment_form = CommentForm(csrf_enabled=False)
    if comment_form.validate_on_submit():
        c_comment = Comment(
                comment_form.post_id.data,
                comment_form.author.data,
                comment_form.text.data)
        db.session.add(c_comment)
        db.session.commit()
    return redirect(url_for('view',post_id=post_id))
Esempio n. 30
0
def post_content(slug):

    try:
        post = Post.query.filter(Post.slug==slug).filter(Post.visible==True).first() or \
            Post.query.filter(Post.slug==slug).filter(Post.author==session.get('username')).first()
        tags = post.tags
        time = post.created.strftime('%H:%M (%d %B %Y)')
        author = post.author
        user = Knot.query.filter(Knot.username == author).first()
        comments = post.comments
    except AttributeError:
        return redirect('/blog/')

    form = CommentForm(request.form)

    if request.method == 'POST' and form.validate_on_submit():
        if 'username' in session:
            try:
                comment = Comment(text=form.text.data,
                                  author=session['username'],
                                  owner=post)
                db.session.add(comment)
                db.session.commit()
                flash('Comment create')
            except Exception as e:
                print(f'Something wrong\n{e.__class__}')
                raise e
            return redirect(url_for('posts.post_content', slug=slug))
        else:
            return redirect(url_for('login.log_in'))

    #### change comment time format to '19 <Month> 2020 (<Week day>) 20:23' ####
    for comment in comments:
        timedelta = int(datetime.now().strftime("%d")) - int(
            comment.created.strftime("%d"))
        if timedelta == 1:
            comment.created = comment.created.strftime("{}%H:%M").format(
                f'{lang[local]["comment"][0]}')
        elif timedelta >= 0:
            comment.created = comment.created.strftime("{}%H:%M").format(
                f'{lang[local]["comment"][1]}')
        else:
            comment.created = comment.created.strftime("%d %B %Y (%A) %H:%M")

    return render_template(
        'post_content.html',
        post=post,
        tags=tags,
        time=time,
        author=author,
        user=user,
        comments=comments,
        form=form,
        slug=slug,
    )
Esempio n. 31
0
def question(question_id):
    question = Question.objects.get(id=question_id)
    form = CommentForm()
    if current_user.is_authenticated():
        if form.validate_on_submit():
            body = form.body.data
            comment = Comment(username=current_user.username, body=body)
            question.update(add_to_set__comments=comment)
            question.save()
            return redirect("/question/%s" % question_id)
    return render_template('question.html', question=question, form=form)
Esempio n. 32
0
def singleIssueCall(id):
    form = CommentForm()
    if not ('username' in session):
        return redirect(url_for('login'))

    if form.validate_on_submit():
        text = form.text.data
        commentID = uuid.uuid1().__str__()
        issueID = id
        problemID = mongo.db.Issues.find_one({'IssueID': issueID})['ProblemID']
        user_name = session['username']
        date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

        issueToChange = mongo.db.Issues
        number = issueToChange.find_one({'IssueID': issueID})['commentNumber']
        issueToChange.update_one(
            {'IssueID': issueID},
            {
                '$set': {'commentNumber': number + 1}
            }
        )

        comments = mongo.db.Comment
        comments.insert({'ID': commentID,
                         'ProblemID': problemID,
                         'IssueID': issueID,
                         'UserName': user_name,
                         'Date': date,
                         'Text': text})
        # return redirect(url_for('singleIssue', id=issueID))

    issue = mongo.db.Issues.find_one({'IssueID': id})
    problemsdb = mongo.db.problems
    problemName = ''
    if issue['ProblemID'] != 'CodeFlask':
        problemName = problemsdb.find_one({'myid': issue['ProblemID']})['name']
    else:
        problemName = 'CodeFlask'

    comment_array = []
    comments = mongo.db.Comment.find({}).sort("Date", -1)
    for comment in comments:
        if id == comment['IssueID']:
            comment_array.append(Comment(comment['ID'],
                                         comment['UserName'],
                                         comment['IssueID'],
                                         comment['ProblemID'],
                                         comment['Text'],
                                         comment['Date']))

    issue = Issue(issue['IssueID'], issue['UserName'], issue['Title'],
                  issue['ProblemID'], problemName, issue['text'], issue['date'].split(" ")[0],issue['commentNumber'])

    return form,comment_array, issue
Esempio n. 33
0
def show_post(post_id):
    requested_post = BlogPost.query.get(post_id)
    form = CommentForm()
    comments = Comment.query.filter_by(parent_post=post_id).all()
    users = User.query.all()
    if form.validate_on_submit():
        new_comment = Comment(comment=form.comment.data, comment_author=current_user, comments=requested_post)
        db.session.add(new_comment)
        db.session.commit()
        return redirect(url_for('get_all_posts'))
    return render_template("post.html", post=requested_post, form=form, comments=comments, users=users)
Esempio n. 34
0
def algo(idnum):
    form = CommentForm()
    algorithm = Algorithm.query.get(idnum)
    comment_list = algorithm.comments.all()
    if not algorithm:
        return redirect(url_for('algos'))
    if form.validate_on_submit():
        post = Comment(name=form.name.data, body=form.body.data, timestamp=datetime.utcnow(), comment=algorithm)
        db.session.add(post)
        db.session.commit()
        return redirect('algos/id/' + str(idnum))
    return render_template('info/algo.html', title=HEADER + algorithm.name, post=algorithm, form=form, comments=comment_list) 
Esempio n. 35
0
def index():
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(
            form.text.data,
            datetime.datetime.now()
        )
        db.session.add(comment)
        db.session.commit()
        return redirect(url_for('index'))
    comments = Comment.query.order_by(db.desc(Comment.timestamp))
    return render_template('index.html', comments=comments, form=form)
Esempio n. 36
0
def recipe(id):
    comment_form = CommentForm()
    if comment_form.validate_on_submit():
        new_comment = comment_form.comment.data
        comments[id].append(new_comment)
    return render_template("recipe.html",
                           template_recipe=recipes[id],
                           template_description=descriptions[id],
                           template_ingredients=ingredients[id],
                           template_instructions=instructions[id],
                           template_comments=comments[id],
                           template_form=comment_form)
Esempio n. 37
0
def show_post(post_id):
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(
            author_id=current_user.id,
            post_id=post_id,
            text=form.comment.data
        )
        db.session.add(comment)
        db.session.commit()
    requested_post = BlogPost.query.get(post_id)
    return render_template("post.html", post=requested_post, form=form)
Esempio n. 38
0
def show_book(book_ind):
    form = CommentForm()
    if request.method == 'POST' and form.validate_on_submit():
        user_name = request.form['user_name']
        comment = request.form['comment']
        comment = Comment(user_name, comment, book_ind)
        comment.save()
    book = Book.query.get(book_ind)
    if not book:
        return 'There is not book from this ID'
    # print(book.comments.all())
    return render_template('book.html', products=book, form=form)
Esempio n. 39
0
def comments(name):
	allprojects = parse()
	currproj = allprojects.getProject(name)
	form = CommentForm()
	commentObj = db.session.query(Comment).filter(Comment.project_name == name)
	if form.validate_on_submit():
		c = Comment(user_name=form.username.data, content=censor(form.comment.data), project_name = name, timestamp = datetime.now())
		db.session.add(c)
		db.session.commit()
		flash("Comment successfully posted")
		return redirect('/comments/'+ name)
	return render_template("comments.html", project = currproj, form = form, commentData = commentObj)
Esempio n. 40
0
def comment(slug):
    """ Creating/adding new comment """
    form =CommentForm()
    
    if form.validate_on_submit():

        new_comment=Comment(con_id=slug,content=form.comment.data,time=datetime.datetime.now(),user=current_user.username)
        db.session.add(new_comment)
        db.session.commit()
        return redirect(url_for('index'))

    return render_template('comment.html', form=form,id=slug)            
Esempio n. 41
0
def show_post(post_id):
    form = CommentForm()
    requested_post = BlogPost.query.get(post_id)
    if form.validate_on_submit():
        new_comment = Comment(text=form.comment.data,
                              comment_author=current_user,
                              parent_post=requested_post)
        db.session.add(new_comment)
        db.session.commit()
    return render_template("post.html",
                           post=requested_post,
                           current_user=current_user,
                           form=form)
Esempio n. 42
0
def post(id):
    # 详情页
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        if 'sec_code' in session and session['sec_code'] != form.verification_code.data:
            flash(lazy_gettext('验证码错误,请刷新!'))
            return  render_template('posts/detail.html', title=post.title, form=form, post=post)
        else:
            comment = Comment(author=current_user, body=form.body.data, post=post)
            db.session.add(comment)
            db.session.commit()
    return render_template('posts/detail.html', title=post.title, form=form, post=post)
Esempio n. 43
0
def show_community_post(community, post_id):
    c = Community.query.filter_by(name=community).first()
    post = Posts.query.get(post_id)
    form = CommentForm()
    if form.validate_on_submit():
        user = g.user
        if c.is_joined(user):
            content = request.form['content']
            comment = Comments(content=content, author=user, post=post)
            db.session.add(comment)
        else:
            flash("Need to be part of the community to add comments")

    return render_template("show_post.html", c=c, post=post, form=form)
Esempio n. 44
0
def viewpost(post_number):
    error = None
    form = CommentForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            new_comment = Comment(
                form.name.data,
                form.email.data,
                form.comment.data,
                post_number
            )
            db.session.add(new_comment)
            db.session.commit()
    return render_template('specificpost.html', posts=specific_post(post_number), comments=comments(post_number), form=form, latest_post=latest_post())
Esempio n. 45
0
def view_video(video_number):
    error = None
    form = CommentForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            new_comment = videoComment(
                form.name.data,
                form.email.data,
                form.comment.data,
                video_number
            )
            db.session.add(new_comment)
            db.session.commit()
    return render_template('specificvideo.html', videos=specific_video(video_number), comments=videoComments(video_number), form=form, latest_video=latest_video())
Esempio n. 46
0
def comment():
    commentform = CommentForm()

    if commentform.validate_on_submit():
        comment = Comment(
            commentform.author.data,
            commentform.text.data,
            datetime.datetime.now(),
            commentform.post_id.data
        )
        db.session.add(comment)
        db.session.commit()
        sendmail("New comment from " + commentform.author.data, request.url_root + "post/" + commentform.post_id.data)

    return redirect('/post/' + commentform.post_id.data)
Esempio n. 47
0
def project_issue(num):
    issue = Issue.objects(number=num)[0]
    child_issues = Issue.objects(base_issue=num)
    comment = Comment()
    form = CommentForm(request.form, comment)
    if form.validate_on_submit():
        form.populate_obj(comment)
        comment.author = session['user_id']
        issue.comments.append(comment)
        issue.save()
        return redirect('/projects/issues/' + num)
    return render_template('projects_issue.html',
                           issue=issue,
                           child_issues=child_issues,
                           form=form)
Esempio n. 48
0
def comment(question_id):
    form = CommentForm()
    question = Questions.query.filter_by(id=question_id).first()
    if not question:
        flash('Question no')
        return redirect(url_for('questions'))
    if form.validate_on_submit():
        comment_text = request.form['comment']
        user = g.user.id
        comment = Comments(comment_text, user, question.id)
        db_session.add(comment)
        db_session.commit()
        flash('Your comment add')
        return redirect(url_for('questions'))
    return render_template('comments.html', title='Comments', question=question, form=form)
Esempio n. 49
0
def submit_comment(username):
    if not g.user:
        flash("You are not authorized for that action.")
        return redirect(url_for("views.profiles"))
    form = CommentForm(request.form)
    user = User.get_user(username)
    if form.validate_on_submit():
        commenter = g.user
        comment = Comment(user.id, commenter.id, form.comment.data)
        db.session.add(comment)
        db.session.commit()
        return redirect(url_for("views.profile", username=user.username))

    flash("There was an error with you comment.")
    return redirect(url_for("views.profile", username=user.username))
Esempio n. 50
0
def view_individual(id):
	form = CommentForm()
	issue = Issue.query.get_or_404(id)
	comment = None
	if form.validate_on_submit():
		comment = Comment(comment=form.comment.data,
						   user=current_user._get_current_object())
		db.session.add(comment)
		db.session.commit()
		flash('Thanks! Your comment has been added.')
	comments = Comment.query.all()
	return render_template('issues/view-individual.html', form=form, issue=issue, comment=comment, comments=comments, title = "Add A Comment")


	
Esempio n. 51
0
def view_post(id, slug=None):
    post = models.Post.query.get_or_404(id)
    comment_form = CommentForm()
    if post.slug != slug:
        return redirect(url_for('view_post', id=id, slug=post.slug))
    if request.method == 'POST':
        if comment_form.validate_on_submit():
            body = comment_form.body.data
            c = models.Comment(body=body)
            post.comments.append(c)
            db.session.add(post)
            db.session.add(c)
            db.session.commit()
            flash('Comment created')
            return redirect(url_for('view_post', id=id, slug=post.slug))
    return render_template("post.html", post=post, comment_form=comment_form)
Esempio n. 52
0
File: views.py Progetto: webNO5/web
def article(a):
    form = CommentForm()
    article=Article.query.filter_by(id=a).first()
    if request.method == 'POST':
        if form.validate_on_submit():
    	    body = form.data['body']
    	    username=User.query.filter_by(id=g.user.id).first().username
	    c=Comment(username=username,body=body,timestamp=datetime.datetime.now(),article_id=a)
	    try:
	        db.session.add(c)
	        db.session.commit()
	        flash(u'评论成功')
	    except Exception, e:
	        flash(u'操作失败')
	    comment=Comment.query.filter_by(article_id=a).all()
	    return render_template('article.html', title = 'article',form=form,article=article,comment=comment)
Esempio n. 53
0
def create_commment(post_id):
    post = BlogPost.query.filter_by(id=post_id).first()
    form = CommentForm()
    if form.validate_on_submit():
        title = form.title.data
        content = form.content.data

        comment = Comment(
            post_id=post_id,
            user_id=current_user.id,
            title=title,
            content=content
        )
        db.session.add(comment)
        db.session.commit()
        flash('Komentar shranjen OK')
        return redirect(url_for('blog.blog_details',post_id=post_id))
Esempio n. 54
0
def item(id):
     user = g.user
     shop=Shop.query.filter_by(id=id).first()
     form=CommentForm()
     if form.validate_on_submit():
         q=Comment(name=g.user.nickname,comment=form.comment.data,item_id=id)
         db.session.add(q)
         db.session.commit()
         return redirect(url_for('index'))
     else:
         comments=Comment.query.filter_by(item_id=id)
     return render_template('item.html',
                            user=user,
                            shop=shop,
                            form=form,
                            comments=comments
                           )
Esempio n. 55
0
def post(id):
    post=Post.query.get_or_404(id)
    form=CommentForm()
    if form.validate_on_submit():
        comment=Comment(body=form.body.data,post=post,author=current_user._get_current_object())
        db.session.add(comment)
        flash("your commnet has been published")
        return redirect(url_for('.post',id=post.id,page=-1))
    page=request.args.get('page',1,type=int)
    if page==-1:
        page=(post.comments.count()-1) // \
            current_app.config['FLASKY_COMMENTS_PER_PAGE']+1
    pagination=post.comments.order_by(Comment.timestamp.desc()).paginate(
        page,per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],error_out=False
    )
    comments=pagination.items
    return render_template('post.html',posts=[post],form=form,pagination=pagination,comments=comments)
Esempio n. 56
0
def comment_create(article_id):
	form = CommentForm()
	if request.method == 'POST':
		if form.validate_on_submit():
			comment = Comment(
				author=form.author.data,
				email=form.mail.data,
				content=form.content.data,
				password=form.password.data,
				article_id=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, active_tab='comment_create')
Esempio n. 57
0
def novelty_discussion(novelty_id):
    novelty = Novelty.query.filter(Novelty.id == novelty_id).first()
    if not novelty:
        abort(404)
    if novelty.comments().count() == 0:
        flash("Ole esimene, kes artiklit kommenteerib!")
    form = CommentForm()
    if form.validate_on_submit() and not form.nickname.data:
        comment = Comment(body=form.comment.data,
                          timestamp=datetime.utcnow(),
                          nickname=form.nimi.data,
                          novelty_id=novelty_id)
        db.session.add(comment)
        db.session.commit()
        flash('Kommentaar lisatud!')
        return redirect(url_for('novelty_discussion', novelty_id=novelty_id))
    return render_template('novelty_discussion.html', title=novelty.headline,
                           novelty=novelty, form=form)