def add_comment(): form = CommentForm() form['csrf_token'].data = request.cookies['csrf_token'] new_comment = Comment( user_id=request.form['userId'], song_id=request.form['songId'], comment=request.form['comment'], ) db.session.add(new_comment) db.session.commit() data = new_comment.to_dict() user = User.query.get(data['user_id']).to_dict() data['userProfileURL'] = user['profile_URL'] data['username'] = user['artist_name'] return data
def comment(post_id): post = Post.query.filter_by(id=post_id).first_or_404() if request.method == "POST": comment = Comment(text=request.form["comment"], user_id=current_user.id, post_id=post.id) db.session.add(comment) db.session.commit() flash("Your Comment Has Been Added To The Post Successfully!", "success") return redirect(url_for("dashboard")) return render_template("dashboard.html")
def post(id): # Detail 详情页 post = Post.query.get_or_404(id) # 评论窗体 form = CommentForm() # 保存评论 if form.validate_on_submit(): 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)
def create_comment(post_id): post = Post.query.get(post_id) form = CreateComment() if form.validate_on_submit(): comment = Comment() if not form["comment_id"].data: thread = Thread(post_id=post.id) db.session.add(thread) db.session.commit() form["thread_id"].data = thread.id form["path"].data = f"{post.id}" form["level"].data = 1 form.populate_obj(comment) db.session.add(comment) db.session.commit() return comment.to_dict() return {"errors": validation_errors_to_error_messages(form.errors)}
async def api_create_comment_v2(id, request, *, content, time): user = request.__user__ check_user(user, check_admin=False) check_string(content=content) blog = await Blog.find(id) if blog is None: raise APIResourceNotFoundError('Blog') comment = Comment(blog_id=blog.id, user_id=user.id, user_name=user.name, user_image=user.image, content=content.lstrip('\n').rstrip()) await comment.save() comments = await Comment.findAll('blog_id = ? and created_at > ?', [id, time], orderBy='created_at desc') return dict(comments=[c.to_json(marked=True) for c in comments])
def comment(request): if request.method == "POST": if not request.body is None: if User.objects.filter(user=request.POST['user']).exists(): d = timezone.localtime(timezone.now()) comment = Comment( board=Board.objects.get(id=request.POST['board_id']), user=User.objects.get(user=request.POST['user']), content=request.POST['content'], date=d.strftime('%Y-%m-%d %H:%M:%S')) comment.save() return JSONResponse('') return HttpResponse(status=400) else: return HttpResponse(status=400) else: return HttpResponse(status=400)
def new_comment(sha1): """Inserts a new comment.""" text = request.form.get("comment_text") submission = Submission().query.filter_by(sha1=sha1).first() comment = Comment(text=text, submission_id=submission.id, user_id=current_user.id, date=datetime.now().strftime("%d/%m/%Y %H:%M:%S")) db.session.add(comment) try: db.session.commit() except DataError: flash("Your comment is too long!") return redirect(request.referrer)
def thread(id): thread = Thread.query.filter_by(id=id).first() if thread is None: return abort(404) form = CommentForm() if current_user.is_authenticated and form.validate_on_submit(): comment = Comment(body=form.body.data, author=current_user, thread=thread) db.session.add(comment) db.session.commit() return redirect(url_for('main.thread', id=thread.id)) comments = thread.comments return render_template("thread.html", thread=thread, comments=comments, form=form)
def blog_page(): global KAFENUT_NOTES id = request.args.get('id') if id: id = int(id) blog = Blog.query.filter_by(id=id).first() if blog is None: flash('No such blog!') return redirect('/index') if request.method == 'GET': return render_template('blog_page.html', blog=blog, kafenut_notes=KAFENUT_NOTES) if g.user is None: #if method==POST(receiving a comment) flash('You need to log in to commend!') return render_template('index', kafenut_notes=KAFENUT_NOTES) Get = request.form.get if not Get('under_cmmt_id'): #if it is a comment to blog cmmt = Comment(to_blog=blog, body=Get('body'), upload_time=datetime.utcnow(), author=g.user) else: under_cmmt = Comment.query.filter_by(id=Get('under_cmmt_id')).first() if under_cmmt is None: flash('No such comment!') return redirect('/index') if Get('to_cmmt_id'): cmmt = Sub_Comment(under_cmmt=under_cmmt, to_blog=blog, to_cmmt_id=Get('to_cmmt_id'), body=Get('body'), upload_time=datetime.utcnow(), author=g.user) else: cmmt = Sub_Comment(under_cmmt=under_cmmt, to_blog=blog, body=Get('body'), upload_time=datetime.utcnow(), author=g.user) db.session.add(cmmt) db.session.commit() flash('Comment successfully!') return redirect(url_for('blog_page') + '?id=' + str(id))
def view_post(id): posts = Post.query.filter_by(id=id).first_or_404() comments = Comment.query.filter_by(post_id=posts.id).all() form = CommentForm() if form.validate_on_submit(): comment = Comment(content=form.content.data, post=posts, author=current_user.username) db.session.add(comment) db.session.commit() flash('Your comment is now live!') return redirect(url_for('view_post', id=id)) return render_template('view_post.html', posts=posts, comments=comments, form=form)
def add_comment(): json = request.json user_id = json.get('user_id') question_id = json.get('question_id') comment_detail = json.get('comment_detail') if not user_id or not type(user_id) == int or not question_id or not type( question_id) == int: return json_data(0, 'bad request') comment = Comment(comment_detail, user_id, question_id) db.session.add(comment) try: db.session.commit() except Exception, e: db.session.rollback() return json_data(0, e.message)
def post_detail(post_id): post = Post.objects(id=post_id).first() form = CommentForm() if form.validate_on_submit(): comment = Comment( content=form.content.data, comment_id=generate_password_hash(form.content.data), author=User.objects(username=current_user.username).first(), author_name=current_user.username, create_time=datetime.utcnow()) post.comments.append(comment) post.save() return redirect(url_for('post_main.post_detail', post_id=post.id)) return render_template('post/post_detail.html', title='微博全文', post=post, form=form)
def post_details(post_id): post = Post.query.filter_by(id=post_id).first_or_404() form = CommentForm() if form.validate_on_submit(): comment = Comment(body=form.comment.data, post_id=post.id, user_id=current_user.id) db.session.add(comment) db.session.commit() flash('comment successful') return redirect(url_for('main.post_details', post_id=post_id)) comments = Comment.query.filter_by(post_id=post_id).order_by( Comment.timestamp.desc()) return render_template('post_details.html', post=post, form=form, comments=comments)
def blog(title): if request.method == "GET": blog = Blog.query.filter_by(title=title).first_or_404() comments = list(subComments(Comment.query.filter_by(blog=blog.id).all())) print(blog.id) print(Comment.query.filter_by(blog=blog.id).all()) pprint(comments) return render_template('blog.html', content=blog, comments=comments, **context) else: try: data = request.get_json() c = Comment(**data) db.session.add(c) db.session.commit() except: return "False" return "True"
def single(_id_): form = CommentForm() if form.validate_on_submit(): comm = Comment(content=form.text.data, user_id=current_user.id, blog_id=_id_) blog = Blog.query.filter(Blog.id == _id_).first() blog.commentnum += 1 db.session.add(blog) db.session.add(comm) return redirect(url_for('posts.single', _id_=_id_)) post = Blog.query.filter(Blog.id == _id_).first() comments = Comment.query.filter(Comment.blog_id == _id_).all() return render_template('posts/single.html', post=post, form=form, comments=comments)
def addComment(user_id, topic_id, body): """Add a comment to the database and commit the change. args: user_id: int topic_id: int body: string """ ## Initialize comment attributes comment = Comment() comment.user_id = user_id comment.topic_id = topic_id comment.body = body ## add new comment to the database and commit the change db.session.add(comment) db.session.commit() ## Display a message to make sure this works flash('Comment created!','info')
def save_comment(blog_id): comment = request.form.get('comment') print(comment) if comment == '' or None: return jsonify({'error': 'Add a comment please'}) new_comment = Comment(comment=comment, user_id=user.id, blog_id=blog_id) new_comment.save() comment_id = Comment.query.filter_by(comment=comment, user_id=user.id, blog_id=blog_id).first() return jsonify({ 'success': 'Your comment was added', 'comment': comment, 'username': user.username, 'id': comment_id.id, 'blog_id': blog_id })
def post(id): p = Post.query.get_or_404(id) form = CommentForm() if form.validate_on_submit(): comment = Comment(body=form.body.data, post=p, author=current_user._get_current_object()) db.session.add(comment) flash("评论已添加") return redirect(url_for('.post', id=p.id, page=-1)) page = request.args.get('page', 1, type=int) per_page = current_app.config['FLASKY_COMMENTS_PER_PAGE'] if page==-1: #calcuate last page page = (p.comments.count() -1)/ per_page + 1 pagination = p.comments.order_by(Comment.timestamp.asc()).paginate(page, per_page=per_page , error_out=False) comments = pagination.items return render_template('post.html', posts=[p],form=form, comments=comments, pagination=pagination)
def setUp(self): ''' Set up method that will run before every Test ''' self.user = User(username='******', password='******', email='*****@*****.**') self.new_comment = Comment(comment='comment', pitch_id=1, user_id=self.user) self.new_pitch = Pitch(id=1, title="Pitch", body='pitches', category='Interview', writer=self.user, comment=self.new_comment)
def post_comment(): form = g.comment_form post_id = request.form['id'] body = request.form['comment'] post = Post.query.filter_by(id=post_id).first() language = guess_language(body) if language == 'UNKNOWN' or len(language) > 5: language = '' comment = Comment(body=body,language=language,post_id=int(post_id),user_id=current_user.id) db.session.add(comment) db.session.commit() return jsonify({ 'comment_num':post.comments.count(), 'avatarURL':current_user.avatar(70), 'comment_username':current_user.username, })
def new_comment(post_id): post = Post.query.get_or_404(post_id) form = CommentForm() if form.validate_on_submit(): comment = Comment(comment=form.comment.data, author=current_user, post_id=post_id) db.session.add(comment) db.session.commit() # comments = Comment.query.all() flash('You comment has been created!', 'success') return redirect(url_for('posts.post', post_id=post.id)) return render_template('new-content.html', title='New Comment', form=form, legend='New Comment')
def setUp(self): ''' Set up method that will run before every Test ''' self.user_Sophy = User(username='******', password='******', email='*****@*****.**') self.new_comment = Comment(comment_content='Awesome stuff', pitch_id=12345, user_id=self.user_Sophy) self.new_pitch = Pitch(id=12345, pitch_title="First Pitch", content='Awesome pitch for stuff', category='Interview Pitch', author=self.user_Sophy, comments=self.new_comment)
def new_comment(post_id): post = Post.query.get_or_404(post_id) page = request.args.get('page', 1, type=int) form = CommentForm() if form.validate_on_submit(): body = form.body.data author = current_user._get_current_object() comment = Comment(body=body, author=author, post=post) replied_id = request.args.get('reply') if replied_id: comment.replied = Comment.query.get_or_404(replied_id) db.session.add(comment) db.session.commit() flash('评论发表成功。', 'success') return redirect(url_for('post.show_post', post_id=post_id, page=page))
def blog_single(id): form = CommentForm() context = { 'post': Post.query.get(id), 'form': form, 'comments': Post.query.get(id).comments.all() } if form.validate_on_submit(): db.session.add( Comment(name=form.name.data, email=form.email.data, body=form.body.data, post_id=id)) db.session.commit() return redirect( url_for('blog_single', id=id, _anchor='section-comments')) return render_template('blog-single.html', **context)
def post_comment(posts_id): post = Post.query.get_or_404(posts_id) form = CommentForm() if form.validate_on_submit(): comment = request.form.get('comment') comment = Comment(comment=comment, posts_id=posts_id, user_id=current_user.username) db.session.add(comment) db.session.commit() flash('Your comment has been posted') return redirect(url_for('.post', posts_id=posts.id)) comments = post.comment.query_all() return render_template('home.html', post=post, form=form, title='Comment')
def post_detail(post_id=''): post = Blog.objects(id=post_id).first() form = comment_form(request.form) if request.method == 'POST': comment = Comment( content=form.content.data, comment_id=generate_password_hash(form.content.data), author=User.objects(username=current_user.username).first(), author_name=current_user.username, create_time=datetime.utcnow()) post1 = Blog.objects(id=post_id).first() post1.comments.append(comment) post1.save() return redirect(url_for('post_main.post_detail', post_id=post1.id)) return render_template('post/post_detail.html', post=post, form=form)
def commitComment(): content = request.args.get('content') user_id = request.args.get('uid') video_id = request.args.get('vid') if content == None or video_id == None: return formattingData(code=-1, msg='Args missing.', data=[]) elif user_id == None: user_id = None try: com = Comment(content=content, user_id=user_id, video_id=video_id) db.session.add(com) db.session.commit() return formattingData(code=200, msg='Submit success', data=[]) except KeyError, e: return formattingData(code=-1, msg='Submit fail.', data=[])
def post(post_id): form = CommentForm() mdform = MdForm() post = Post.query.filter_by(id=post_id).first_or_404() mdform.body.data = post.body comments = Comment.query.filter_by(post_id=post_id).order_by( Comment.timestamp.desc()).all() tags = Tagged.query.filter_by(post_id=post_id).all() liked_cnt = Liked.query.filter_by(post_id=post_id).count() collected_cnt = Collected.query.filter_by(post_id=post_id).count() if form.validate_on_submit(): if current_user.is_authenticated: new_comment = Comment(body=form.body.data, user_id=current_user.id, post_id=post_id) db.session.add(new_comment) db.session.commit() return redirect(url_for('post', post_id=post.id)) else: return redirect(url_for('login')) if not current_user.is_authenticated: isLiked = False isCollected = False else: if Liked.query.filter( and_(Liked.post_id == post_id, Liked.user_id == current_user.id)).count() == 0: isLiked = False else: isLiked = True if Collected.query.filter( and_(Collected.post_id == post_id, Collected.user_id == current_user.id)).count() == 0: isCollected = False else: isCollected = True return render_template('post.html', mdform=mdform, form=form, post=post, liked_cnt=liked_cnt, isLiked=isLiked, comments=comments, collected_cnt=collected_cnt, isCollected=isCollected, tags=tags)
def show_post(slug): logger.info('Mostrando un post') logger.debug(f'Slug: {slug}') post = Post.get_by_slug(slug) if not post: logger.info(f'El post {slug} no existe') abort(404) form = CommentForm() if current_user.is_authenticated and form.validate_on_submit(): content = form.content.data comment = Comment(content=content, user_id=current_user.id, user_name=current_user.name, post_id=post.id) comment.save() return redirect(url_for('public.show_post', slug=post.title_slug)) return render_template("public/post_view.html", post=post, form=form)
def submit(): content = request.form print('comment.submit() content:', content) comment = content.get('comment') project_id = content.get('project_id') parent_id = content.get('parent_id') user_id = current_user.id if comment and project_id and user_id: comment = Comment(text=comment, project_id=project_id, created_by_user_id=user_id, parent_id=parent_id) comment.save() flash('Added comment') else: flash('Unable to add comment', 'error') return redirect(url_for('projectbp.view', project_id=project_id))