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)
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)
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 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)
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)
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)
def show(id): if not g.db.doc_exist(id): abort(404) errors = [] task = Task.get(id) form = CommentForm(request.form) comments = list(Comment.view('comments/by_task_id', key = id)) comments = sorted(comments, key = lambda x: x.date) if request.method == 'POST' and form.validate(): new_comment = Comment() new_comment.author = session['username'] new_comment.text = form.text.data new_comment.date = datetime.datetime.utcnow() new_comment.task_id = id new_comment.save() flash('Comment was successfully added') return redirect(url_for('tasks.show', id = id)) fpath = os.path.join(UPLOADED_FILES, id) files = None if os.path.exists(fpath): files = os.listdir(fpath) errors.extend(format_form_errors(form.errors.items())) return render_template('task_show.html', \ task = task, comments = comments, form = form, errors = errors, \ files = files)
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)
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))
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)
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'))
def comment(request, event_id): ''' Create new Comment. ''' context = RequestContext(request) now = timezone.now() event = get_object_or_404(Event, id=event_id) profile = UserProfile.objects.get(user_id=request.user.id) if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): note = comment_form.save(commit=False) note.author = profile note.event = event note.created = now note.save() return HttpResponseRedirect('/event/%d' % event.id) else: comment_form = CommentForm() return render(request, 'app/comment.html', {'event': event, 'profile': profile, 'comment_form': comment_form} )
def show(id): if not g.db.doc_exist(id): abort(404) errors = [] task = Task.get(id) form = CommentForm(request.form) comments = list(Comment.view('comments/by_task_id', key=id)) comments = sorted(comments, key=lambda x: x.date) if request.method == 'POST' and form.validate(): new_comment = Comment() new_comment.author = session['username'] new_comment.text = form.text.data new_comment.date = datetime.datetime.utcnow() new_comment.task_id = id new_comment.save() flash('Comment was successfully added') return redirect(url_for('tasks.show', id=id)) fpath = os.path.join(UPLOADED_FILES, id) files = None if os.path.exists(fpath): files = os.listdir(fpath) errors.extend(format_form_errors(form.errors.items())) return render_template('task_show.html', \ task = task, comments = comments, form = form, errors = errors, \ files = files)
def event_detail(request, event_id): ''' Get and return all details for the Event with event_id = event_id. ''' now = timezone.now() event = get_object_or_404(Event, id=event_id) profile = UserProfile.objects.get(user_id=request.user.id) participants = all_info_many_profiles(event.participants.all()) owners = all_info_many_profiles(event.owners.all()) comments = Comment.objects.filter(event=event_id) editform = EditEventForm(instance=event) event_over = event.end_time <= now in_progress = event.event_time <= now and now <= event.end_time if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): note = comment_form.save(commit=False) note.author = profile note.event = event note.created = now note.save() return HttpResponseRedirect('/event/%d' % event.id) else: comment_form = CommentForm() context = {'event': event, 'participants': participants, 'owners': owners, 'editform': editform, 'comments': comments, 'comment_form': comment_form, 'event_over': event_over, 'in_progress': in_progress} return render(request, 'app/event_detail.html', context)
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)
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)
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)
def create_comment(request): http_referer = request.META.get('HTTP_REFERER') if not http_referer: return HttpResponseForbidden() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): article_id = form.cleaned_data['article_id'] path = parse.urlparse(http_referer).path a_id = path.split('/')[-1] if int(article_id) != int(a_id): return HttpResponseForbidden() anchor = request.POST.get('err_anchor', '') success, msg = is_valid_comment(form) if not success: return HttpResponseRedirect( reverse('app:detail_article', args=(article_id,)) + '?form_error=' + msg + anchor) # article_meta.comment_num += 1 # article_meta.save() comment = form.save() anchor = request.POST.get('success_anchor', '') anchor += str(comment.id) return HttpResponseRedirect(reverse('app:detail_article', args=(article_id,)) + anchor) else: anchor = request.POST.get('err_anchor', '') article_id = form.cleaned_data['article_id'] return HttpResponseRedirect( reverse('app:detail_article', args=(article_id,)) + '?form_error=' + '验证码错误' + anchor)
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)
def news_replies(id): form = CommentForm() comments = Comments_news.query.filter_by(id=id).first() if form.validate(): reply = Replies_news(datetime.datetime.now(),form.body.data,form.author.data,id) db.session.add(reply) db.session.commit() return render_template('news_comment.html',comment=comments,form=form)
def post(self, request, pk): form = CommentForm(request.POST) if form.is_valid(): self.object = form.save(commit=False) self.object.user = get_object_or_404(User, pk=self.request.user.id) self.object.tweet = get_object_or_404(Tweet, pk=pk) self.object = form.save() return HttpResponseRedirect(reverse('tweet-detail', args=(pk, )))
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')
def comment_create(request, pk): if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): post = Post.objects.get(id=pk) Comment.objects.create(created_by=request.user, post=post, **form.cleaned_data) return redirect(reverse_lazy("post_detail", kwargs={"pk": pk}))
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)
def news_replies(id): form = CommentForm() comments = Comments_news.query.filter_by(id=id).first() if form.validate(): reply = Replies_news(datetime.datetime.now(), form.body.data, form.author.data, id) db.session.add(reply) db.session.commit() return render_template('news_comment.html', comment=comments, form=form)
def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): comment = form.save() comment.save() messages = Message.objects.all() cache.set('messages', pickle.dumps(messages)) return HttpResponseRedirect(reverse_lazy('app:message_list')) return HttpResponseRedirect(reverse_lazy('app:message_list'))
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)
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'))
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)
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)
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)
def test_save_creates_associated_comment(self): doc = Document.objects.create() form = CommentForm(doc, {'comment': 'Hello World'}) form.full_clean() comment = form.save() self.assertEqual(doc.comment_set.count(), 1) self.assertEqual(Comment.objects.all().count(), 1) self.assertEqual(comment.document, doc)
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)
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)
def comment(id): form = CommentForm() phon = "" phones = [Samsung,Apple,Microsoft,Nokia,Sony,LG,HTC,Motorola,Huawei,Lenovo,Xiaomi,Acer,Asus,Oppo,Blackberry,Alcatel, ZTE,Toshiba,Gigabyte,Pantech,XOLO,Lava,Micromax,BLU,Spice,Verykool,Maxwest,Celkon,Gionee,Vivo,NIU,Yezz,Parla,Plum] for phone in phones: if not phon: phon = db.session.query(phone).filter_by(phoneId=id).first() if form.validate(): comment = Comments(id,datetime.datetime.now(),form.body.data,form.author.data) db.session.add(comment) db.session.commit() return render_template('comment.html',phone=phon,form=form)
def news_comment(id): form = CommentForm() cur = mysql.connect().cursor() sql = "select newsid, Picture, Content, Name from news WHERE newsid=%s" %(id) cur.execute(sql) news = cur.fetchone() p = re.compile(r'<.*?>') new = p.sub('', news[2]) if form.validate(): comment = Comments_news(newsid=id,created_at=datetime.datetime.now(),body=form.body.data,author=form.author.data) db.session.add(comment) db.session.commit() return render_template('news_comment.html',news=news,new=new,form=form)
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)
def singlebook(request, book_id): if request.user.is_authenticated(): print(book_id) book = Book.objects.get(id=int(book_id)) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): cd = form.cleaned_data comment = BookComment(body=cd['body']) comment.post = book comment.save() comments = book.comments.all commentform = CommentForm() ctx = {'book':book, 'form':commentform, 'comments':comments} ctx.update(csrf(request)) return render_to_response('app/single_book.html', ctx) else: return render_to_response('app/index.html')
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)
def add_comment(request, article_id): """Add a new comment.""" template = "comment.html" if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): temp = form.save(commit=False) temp.user = request.user temp.date = datetime.datetime.now() temp.article_id = article_id temp.save() return HttpResponseRedirect('/accounts/articles/comments/'+str(article_id)) else: form = CommentForm() try: comments = Comment.objects.filter(article_id=article_id) return render_to_response(template, {"form":form, "comments":comments, "article_id":article_id, "full_name":request.user.username},\ RequestContext(request)) except: return render_to_response(template, {"form":form, "article_id":article_id, "full_name": request.user.username}, RequestContext(request))
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)
def post(self, user): # grab the form form = CommentForm(self.request.params) if not form.validate(): form.csrf_token.data = self.generate_csrf() self.r(form) return # get the comment try: comment = Key(urlsafe=form.key.data).get() except: # invalid key comment = None if comment is None: self.redirect('/') return if comment.author != user: self.redirect('/') return # better be a post here or else! post = comment.key.parent().get() if post is None: self.redirect('/') return # update the comment try: comment.content = form.comment.data comment.put() self.redirect('/post/view?key=%s' % post.key.urlsafe()) return except: # let's give them another chance form.csrf_token.data = self.generate_csrf() self.r(form, flashes=flash()) return
def staticUnity(slug): if request.method == 'POST': unity = Unity.get_or_404(slug=slug) form = CommentForm() if not form.validate(): return render_template('unity/staticUnity.html', pageTitle=unity.title, unity=unity, form=form) else: newComment = Comment(body=form.comment.data) newComment.author = User.get(email=current_user.email) unity.comments.append(newComment) unity.save() form.comment.data = None # resets field on refresh flash('Comment Posted') return render_template('unity/staticUnity.html', pageTitle=unity.title, unity=unity, form=form) elif request.method == 'GET': try: return render_template('unity/%s.html' % slug, pageTitle=slug) except TemplateNotFound: unity = Unity.get_or_404(slug=slug) currentUser = User.get(email=current_user.email) if (unity.postType == 'draft' and unity.author != currentUser and currentUser.is_admin() is False): flash('You must be draft author or admin to view.') return redirect(url_for('.listUnity')) else: form = CommentForm() return render_template('unity/staticUnity.html', pageTitle=unity.title, unity=unity, form=form)
def idea(request,idea_id, edit=False): try: idea = Idea.objects.get(id =idea_id) except Idea.DoesNotExist: return HttpResponseRedirect("/") tags = Tag.objects.filter(idea = idea) try: voted_on = idea.vote_on.get(user = request.user) except: pass relevant_comments = Comment.objects.filter(idea = idea).order_by("date_posted") commentForm = CommentForm(request.POST or None) comments_num = len(relevant_comments) if request.method == 'POST': #If something has been submitted if 'vote' in request.POST: voteForm = VoteForm(request.POST) if voteForm.is_valid(): helpers.vote(voteForm,request.user) if 'edit_idea' in request.POST: ideaForm = IdeaForm(request.POST) if ideaForm.is_valid(): clean = ideaForm.cleaned_data idea.idea = clean['idea_content'] idea.elaborate = clean['elaborate'] helpers.filter_tags(clean['tags'], idea) idea.private = clean['private'] idea.save() edit = False return HttpResponseRedirect("/idea/"+str(idea.id)+"/") if 'submit_comment' in request.POST: print "submit" commentForm = CommentForm(request.POST) if commentForm.is_valid(): clean = commentForm.cleaned_data comment = Comment(text = clean['comment'],idea=idea,user = request.user) comment.save() all_comments_idea = Comment.objects.filter(idea = idea) #if the user posting the comment doesn't own the idea, send the email to the user who owns the idea if request.user != idea.user: helpers.send_comment_email(True, request, idea, idea.user.email, comment.text) #add the user who owns the idea to the list, because either they've already received it from above, or they're the ones posting the comment user_emails_sent = [idea.user,] #for every comment on the idea for comment_for_idea in all_comments_idea: #if the commenter is not the request user we want to send the email, but if comment_for_idea.user != request.user: #only if the comment hasn't already been sent an email. if not comment_for_idea.user in user_emails_sent: user_emails_sent.append(comment_for_idea.user) helpers.send_comment_email(False, request, idea, comment_for_idea.user.email, comment.text) return HttpResponseRedirect("/idea/"+str(idea.id)+"/") #encoded_email = user.email voteUpForm = VoteForm({'vote':'+'}) if edit and (idea.user == request.user): tagString = '' for tag in tags: tagString += tag.tag + "," tagString = tagString[0:(len(tagString)-1)] ideaForm = IdeaForm({ 'idea_content':idea.idea, 'elaborate':idea.elaborate, 'tags':tagString}) else: edit = False voteDownForm = VoteForm({'vote':'-'}) commentForm = CommentForm(None) return render_to_response('main/idea.html',locals(), context_instance=RequestContext(request))
def create(self, request, apikey, apisignature): print "creating" if not key_check( apikey, apisignature, '/idea/comment/'): return {'error':'authentication failed'} else: print commentForm = CommentForm({"comment":request.POST['comment']}) if commentForm.is_valid(): print "form valid" clean = commentForm.cleaned_data print clean print request.POST idea = Idea.objects.get(id = request.POST['idea_id']) print idea try: print "trying" comment = Comment( text = clean['comment'], user = User.objects.get(id = request.POST['user_id']), idea = idea) print comment except Idea.DoesNotExist: return {'error':'no idea'} except User.DoesNotExist: return {'error':'no user'} else: comment.save() #helpers.filter_tags(clean['tags'], idea) print comment return comment else: return {'error':'no comment'}