def comments(): from forms import CommentForm from models import Comment if request.method == 'POST': print(request.form) form = CommentForm(request.form) print(form.data, form.validate()) if form.validate(): comment = Comment(**form.data) db.session.add(comment) db.session.commit() all_articles = Article.query.all() all_comments = Comment.query.all() # article_comments = [] # two-dimensional array # for article in all_articles: # comments = Comment.query.filter(article.id == Comment.article_id).all() # article_comments.append(comments) # print(all_articles) # print(article_comments) return render_template('main.txt', articles=all_articles, comments=all_comments)
def single_blog(blogname): form = CommentForm() current_blog = blogname + '.html' if request.method == 'POST': if form.validate() == False: flash("All the fields are required.") return render_template(current_blog, form=form) elif form.validate() == True and form.validate_on_submit(): current_comment = Comment(body=form.body.data, timestamp=datetime.utcnow(), post_id=request.args.get('post_id')) db.session.add(current_comment) return redirect(url_for('single_blog', blogname=blogname, post_id=request.args.get('post_id'))) elif request.method == 'GET': comments = Comment.query.filter_by(post_id=request.args.get('post_id')).all() return render_template(current_blog, form=form, comments=comments)
def post(slug): p=Post.objects.get_or_404(slug=slug) tags=Post.objects.distinct('tags') print request.form form = CommentForm(request.form) print form.data print form.validate() if form.validate(): comment = Comment() form.populate_obj(comment) p.comments.append(comment) p.save() return redirect(url_for('post', slug=slug)) return render_template("post.html", title = p.title, p=p, tags=tags, form=form)
def Comment_fu(Topic_id_to): from models import Comment from forms import CommentForm if request.method == "POST": new_request = request.form.to_dict() new_request["Topic_id"] = Topic_id_to a = MultiDict() for x in new_request: a.add(x, new_request[x]) form = CommentForm(a) if form.validate(): commentsql = Comment(**form.data) db.session.add(commentsql) db.session.commit() else: return render_template("errors.html", errors_text=str(form.errors)), 400 topic_select = Topic.query.filter_by(id=int(Topic_id_to)).first() comments_select = Comment.query.filter_by(Topic_id=int(Topic_id_to)) print() return render_template('_take_comment_template.html', topic=topic_select, comments=comments_select)
def post(move_id): form = CommentForm(csrf_enabled=False) if request.method == "GET": move = g.conn.execute( '''SELECT * from moves WHERE moves.move_id = (%s)''', move_id) fetch = move.fetchone() person = fetch[4] move = fetch[5] comments_data = g.conn.execute( '''SELECT * from comments WHERE comments.move_id = (%s)''', move_id) return render_template("post.html", move=move, comments=comments_data, form=form, person=person) elif request.method == "POST": if not form.validate(): return render_template("post.html", move=move, form=form) else: num = g.conn.execute('''SELECT COUNT(comment_id) FROM comments''') c_id = num.fetchone()[0] c_id = c_id + 201 today = datetime.date.today() g.conn.execute( '''INSERT INTO comments (comment_id, comment, comment_date, move_id, person) VALUES ( (%s),(%s),(%s),(%s),(%s))''', c_id, form.text.data, today, move_id, session['person_name']) return redirect(url_for('feed'))
def comment_create(): data = request.get_json() article = g.article form = CommentForm(**data) if form.validate(): form_data = form.data form_data['user'] = g.user form_data['ip'] = request.remote_addr try: comment = article.create_comment(**form_data) article.update_comment_count() article.update_user_comment_count(user_id=comment.user_id) db_session.commit() cache.update_article(article.id, article) cache.update_sorted_articles(article, 'comment_count') return jsonify({"data": comment.json_data()}) except ModelException, me: db_session.rollback() return json_error(type=me.type, messages=me.message) except Exception, e: logging.error(e) db_session.rollback() return json_error_database()
def show_post(post_id): from models import Comment, Post from forms import CommentForm # Получение определнного поста из базы данных по id из URL post = Post.query.filter_by(id=post_id).first() if post is None: return 'Not Found', 404 # Добавление комментария if request.method == 'POST': form = CommentForm(request.form) if form.validate(): comment = Comment(post=post, content=request.form['content']) db.session.add(comment) # Для поста увеличиваем переменную, хранящую количество комментариев post.number_of_comments += 1 db.session.commit() flash('Комментарий опубликован.') else: flash('Форма не валидна! Комментарий не был опубликован.') # Получение всех комментариев из базы данных к текущему посту comments = Comment.query.filter_by(post_id=post.id).all() # Вывод поста и комментариев к нему return render_template('show_comments.html', post=post, comments=comments)
class PostHandler(MainHandler): def initialize(self, *args, **kwargs): self.form = CommentForm(self.request.arguments) @gen.coroutine def get(self, title): post = yield Post.asyncQuery(title=title).first() if not post: raise tornado.web.HTTPError(404) self.render("post.html", post=post, form=self.form) @gen.coroutine def post(self, title): post = yield Post.asyncQuery(title=title).first() if not post: raise tornado.web.HTTPError(404) if self.form.validate(): comment = Comment() comment.create_time = datetime.datetime.utcnow() comment.author_name = self.form.author_name.data comment.author_email = self.form.author_email.data comment.author_url = self.form.author_url.data # Direct use user post data is unsafe, # so we convert `org_markdown_text` in the back-end comment.content = markdown2.markdown(self.form.content.data) post.comments.append(comment) yield post.save() self.flash("评论提交成功~") return self.redirect("{path}{id}".format( path=self.request.path, id="#comment")) self.render("post.html", post=post, form=self.form)
def comment_create(): data = request.get_json() topic = g.topic form = CommentForm(**data) if form.validate(): form_data = form.data form_data['user'] = g.user form_data['ip'] = request.remote_addr try: comment = topic.create_comment(**form_data) topic.update_comment_count() topic.update_user_comment_count(user_id=comment.user_id) db_session.commit() cache.update_topic(topic.id, topic) cache.update_sorted_topics(topic, 'comment_count') return jsonify({"data": comment.json_data()}) except ModelException, me: db_session.rollback() return json_error(type=me.type, messages=me.message) except Exception, e: logging.error(e) db_session.rollback() return json_error_database()
def comment_new(id): post = Post.get_by_id(id) if post is None or post.is_hidden: abort(404) form = CommentForm() if form.is_submitted(): try: if not form.validate(): raise Exception(_('ERROR_INVALID_SUBMISSION')) comment = Comment(user=current_user, post=post) form.populate_obj(comment) comment.save() flash(_('COMMENT_SAVE_SUCESS')) if comment.parent_comment: send_email('reply_comment', comment) else: send_email('comment', post, comment) return redirect(url_for('stamp.show', id=post.id, _anchor='comment-%s' % comment.id)) except Exception as e: flash(e.message, 'error') return render_template('main/stamp/show.html', post=post, form=form)
def comment_new(id): post = Post.get_by_id(id) if post is None or post.is_hidden: abort(404) form = CommentForm() if form.is_submitted(): try: if not form.validate(): raise Exception(_('ERROR_INVALID_SUBMISSION')) comment = Comment(user=current_user, post=post) form.populate_obj(comment) comment.save() flash(_('COMMENT_SAVE_SUCESS')) if comment.parent_comment: send_email('reply_comment', comment) else: send_email('comment', post, comment) return redirect( url_for('stamp.show', id=post.id, _anchor='comment-%s' % comment.id)) except Exception as e: flash(e.message, 'error') return render_template('main/stamp/show.html', post=post, form=form)
class PostHandler(MainHandler): def initialize(self, *args, **kwargs): self.form = CommentForm(self.request.arguments) @gen.coroutine def get(self, title): post = yield Post.asyncQuery(title=title).first() if not post: raise tornado.web.HTTPError(404) self.render("post.html", post=post, form=self.form) @gen.coroutine def post(self, title): post = yield Post.asyncQuery(title=title).first() if not post: raise tornado.web.HTTPError(404) if self.form.validate(): comment = Comment() comment.create_time = datetime.datetime.utcnow() comment.author_name = self.form.author_name.data comment.author_email = self.form.author_email.data comment.author_url = self.form.author_url.data # Direct use user post data is unsafe, # so we convert `org_markdown_text` in the back-end comment.content = markdown2.markdown(self.form.content.data) post.comments.append(comment) yield post.save() self.flash("评论提交成功~") return self.redirect("{path}{id}".format(path=self.request.path, id="#comment")) self.render("post.html", post=post, form=self.form)
def index2(): from forms import CommentForm if request.method == 'POST': print(request.form) form = CommentForm(request.form) if form.validate(): comment = Comment(**form.data) db.session.add(comment) db.session.commit() flash('Comment created!') else: flash('Form is not valid! Comment was not created.') flash(str(form.errors)) comments = Comment.query.all() # user = User.query.filter(id=posts[0].user_id) # user = posts[0].user for comment in comments: user_id = comment.user_id post_id = comment.post_id user = User.query.filter_by(id=user_id).first() post = Post.query.filter_by(id=post_id).first() print(user, post) return render_template('home.txt', comments=comments)
def add_comment(): form = CommentForm(request.form) if request.method == 'POST' and form.validate(): comment = Comment(comment=form.comment.data, user_id=current_user.get_id()) db.session.add(comment) db.session.commit() return redirect(url_for('add_comment')) return render_template('comment.html', form=form)
def comment(): form = CommentForm(request.form) if request.method == 'POST' and form.validate(): comment = models.Comment(str(uuid.uuid4()),str(form.suggestionid.data),str(session['uuid']),form.comment.data,datetime.datetime.now()) models.db.session.add(comment) models.db.session.commit() flash('Your comment was posted successfully') return redirect(url_for('getonesuggestion',suggestid=form.suggestionid.data)) return redirect(url_for('getonesuggestion',suggestid=form.suggestionid.data))
def comment(filename): if 'logged_in' and 'reviewer' not in session: flash("You Are Not Authorized To Access This Page..!!") return redirect(url_for('login')) form = CommentForm(request.form) if form.validate(): comment_result = commentArticle(form, filename) flash(comment_result) return redirect(request.referrer)
def comment(): form = CommentForm(request.form) if request.method == 'POST' and form.validate(): comment = models.Comment(str(uuid.uuid4()),str(form.suggestionid.data),str(session['uuid']),form.comment.data,datetime.datetime.now()) models.db.session.add(comment) models.db.session.commit() flash('Thanks for the comment') return redirect('/suggestion') return redirect('/suggestion')
def view_ad(url): room = Room.query.filter_by(urlname=url).first() if not room: abort(404) if room.dead or get_days_ago(room.created_at) > OLD_DAYS.days: abort(404) occupied = Occupied.query.filter_by(space=room.occupieds).order_by("created_at").first() if occupied and get_days_ago(occupied.created_at) > OCCUPIED_DAYS.days: abort(404) # URL is okay. Show the ad. comments = Comment.query.filter_by(commentspace=room.comments, parent=None).order_by("created_at").all() commentform = CommentForm() delcommentform = DeleteCommentForm() if request.method == "POST": if request.form.get("form.id") == "newcomment" and commentform.validate(): if commentform.edit_id.data: comment = Comment.query.get(int(commentform.edit_id.data)) if comment: if comment.user == g.user: comment.message = commentform.message.data flash("Your comment has been edited", category="info") else: flash("You can only edit your own comments", category="info") else: flash("No such comment", category="error") else: comment = Comment(user=g.user, commentspace=room.comments, message=commentform.message.data) if commentform.parent_id.data: parent = Comment.query.get(int(commentform.parent_id.data)) if parent and parent.commentspace == room.comments: comment.parent = parent room.comments.count += 1 db.session.add(comment) flash("Your comment has been posted", category="success") db.session.commit() # Redirect despite this being the same page because HTTP 303 is required to not break # the browser Back button return redirect(url_for("view_ad", url=room.urlname) + "#c" + str(comment.id), code=303) elif request.form.get("form.id") == "delcomment" and delcommentform.validate(): comment = Comment.query.get(int(delcommentform.comment_id.data)) if comment: if comment.user == g.user: comment.delete() room.comments.count -= 1 db.session.commit() flash("Your comment was deleted.", category="success") else: flash("You did not post that comment.", category="error") else: flash("No such comment.", category="error") return redirect(url_for("view_ad", url=room.urlname), code=303) return render_template( "room.html", room=room, comments=comments, commentform=commentform, delcommentform=delcommentform )
def display_post(post_id): post = api.Post().get(post_id) comments = api.Comment().get_all(post_id) form = CommentForm(request.form) if request.method == 'POST' and form.validate(): comment = api.Comment().post(user_id=1, content=form.content.data, post_id=1) return render_template('post.html', post=post, comments=comments, form=form)
def comment_new(): form = CommentForm(request.form) if form.validate(): form.quote_id.data = None if form.quote_id.data < 0 else form.quote_id.data c = Comment(form.article_id.data, current_user, form.content.data, form.quote_id.data) db.save(c) return redirect(url_for('Common.article', article_id=form.article_id.data)) return redirect(url_for('Common.index'))
def index(): form = CommentForm() if request.method == "POST": if form.validate() == False: pass else: new_comment = SocialApp(form.name.data, form.comment.data) db.session.add(new_comment) db.session.commit() comments = SocialApp.query.all() return render_template("index.html", form=form, comments=comments)
def view_task(project_key, task_key): project = Project.get_project(project_key) if project is None: abort(404) task = Task.get_task(project, task_key) current_user_id = get_user(request, project_key) form = CommentForm(request.form) if request.method == 'POST' and form.validate(): flash("Your comment was added") task.add_comment(form.comment.data, current_user_id) return redirect( url_for('view_task', project_key=project_key, task_key=task_key)) return render_template('task.html', task=task, project=project, form=form)
def add_comment(): from models import Comment from forms import CommentForm if request.method == 'POST': form = CommentForm(request.form) if form.validate(): comment = Comment(**form.data) db.session.add(comment) db.session.commit() return view_post(comment.post_id) else: return str(form.errors), 400 else: return 'bad method', 400
def post(self, commentID): form = CommentForm(self.request.POST) if self.session.get("username"): user = db.GqlQuery("SELECT * FROM User WHERE username='******'" % self.session.get("username")) userID = user.get().key().id() key = db.Key.from_path('Comments', int(commentID)) comment = db.get(key) if form.validate() and int(comment.authorID) == int(userID): comment.content = form.comment.data comment.put() self.redirect("/") else: self.redirect("/") else: self.redirect("/")
def post(self, postID): if self.session.get("username"): commentForm = CommentForm(self.request.POST) user = db.GqlQuery("SELECT * FROM User WHERE username='******'" % self.session.get("username")) userID = user.get().key().id() if commentForm.validate(): newComment = Comments(content=commentForm.comment.data, authorID=int(userID), postID=int(postID)) newComment.put() self.redirect("/post/%s" % postID) else: self.redirect("/") else: self.redirect("/")
def comment(): from models import Comment from forms import CommentForm form = CommentForm(request.form) if form.validate(): comment = Comment(**form.data) db.session.add(comment) db.session.commit() result = {"status":True, "statusText": "Всё прошло успешно"} else: flash(str(form.errors)) result = {"status": False, "errors": form.errors} return jsonify(result)
def list_events(): # selected timespan for events. by default ([0]) set to future events # [1] = next week # [2] = this month # [3] = everything in the past ts = int(request.args.get('timespan', 1))-1 ts_req= ["E.day >= now()", "(E.day::date - now()::date) >= 0 AND (E.day::date - now()::date) <= 7",\ "EXTRACT(MONTH FROM now())=EXTRACT(MONTH FROM E.day) AND EXTRACT(YEAR FROM now())=EXTRACT(YEAR FROM E.day)",\ "E.day < now()"] form = CommentForm(request.form) s_form = SignForm(request.form) if request.method == "GET": listed_events = events.get_all_events(ts_req[ts]) sign_ups = events.get_all_sign_ups(ts_req[ts]) sign_outs = events.get_all_sign_outs(ts_req[ts]) comments = events.get_all_comments(ts_req[ts]) if users.is_admin(): mod_rights = True else: mod_rights = False return render_template("events_list.html", events=listed_events, sign_ups=sign_ups, sign_outs=sign_outs, comments=comments, form=form, s_form=s_form, mod_rights=mod_rights) if request.method == "POST": if users.get_csrf_token() != form.csrf_token.data: return render_template("error.html", message="Kielletty!") if form.submit.data and form.validate(): if events.add_comment(form.user_id.data, form.event_id.data, form.message.data): return redirect("/events") else: return render_template("error.html", message="Kommentin lisääminen ei onnistunut") if s_form.player_in.data and s_form.validate(): if events.sign_up(s_form.user_id.data, s_form.event_id.data, "t"): return redirect("/events") else: return render_template("error.html",message="Ilmoittautuminen ei onnistunut") elif s_form.validate() and s_form.player_out.data: if events.sign_up(s_form.user_id.data, s_form.event_id.data, "f"): return redirect("/events") else: return render_template("error.html",message="Ilmoittautuminen ei onnistunut")
def home(id): from models import Post, Comment from forms import PostForm, CommentForm if request.method == 'POST': print(request.form) form = CommentForm(request.form) if form.validate(): comment = Comment(**form.data) db.session.add(comment) db.session.commit() flash('Comment created!') post = Post.query.filter_by(id=id).first() comments = Comment.query.filter_by(post_id=id) return render_template('article.html', post=post, comments=comments)
def comment_create(): if request.method == 'POST': c_form = CommentForm(request.args) if c_form.validate(): comment = Comment( post=Post.query.filter_by(id=request.args['id_post']).first(), comment_content=request.args['comment_content'], id_post=request.args['id_post']) db.session.add(comment) db.session.commit() all_comments_post = Comment.query.filter_by( id_post=request.args['id_post']).all() return render_template('create_comment.txt', comment=comment, all_comments_post=all_comments_post) else: return jsonify(c_form.errors)
def create(article_id): if not check_permission(current_user, 'comment'): flash('你没有权限') return redirect(url_for('Article.retrieve', article_id=article_id)) form = CommentForm(request.form) if form.validate(): article = Article.query.get(article_id) raw_content = form.content.data def _replace(matched): user = User.query.filter_by(username=matched.group('username')).first() return "<a href=" + url_for('User.profile', user_id=user.id) + ">@{username}</a>:"\ .format(username=matched.group('username')) html_content = re.sub(r'@(?P<username>[^:]+):', _replace, raw_content) comment = Comment(article.id, current_user.id, html_content) comment.save() return redirect(url_for('Article.retrieve', article_id=article_id))
def get_comment(): form = CommentForm(request.form) if form.validate(): if captcha_validate(form.hash_key.data, form.recaptcha.data): comment = Comment(form.name.data, form.body.data, form.content_type.data, form.content_id.data) db.session.add(comment) db.session.commit() if request.is_xhr: return jsonify(comment_created=True) else: flash(u'Thanks for your comment') else: if request.is_xhr: return jsonify(form.errors['recaptcha'] = u'The symbol from the image do not match') else: flash(u'Fields are not correctly') return redirect(request.values.get('next')+'#comments')
def article(article_id): from forms import CommentForm from models import Comment if request.method == 'POST': form = CommentForm(request.form) if form.validate(): comment = Comment(**form.data) db.session.add(comment) db.session.commit() this_article = Article.query.filter_by(id=article_id).first() comments = Comment.query.filter_by(article_id=this_article.id) return render_template('article.html', article=this_article, comments=comments)
def post_comment(): from models import Post, Comment form = CommentForm(request.form) if form.validate(): model = Comment() form.populate_obj(model) model.post = Post.query.filter_by(id=model.post_id).first() db.session.add(model) db.session.commit() comment = model.post.comments.order_by(Comment.id.desc()).first() return jsonify(comment.serialize) else: abort(500)
def video(id): data = Videos.query.get(id) form = CommentForm(request.form) if request.method == 'POST' and form.validate(): user = Users.query.filter_by(username=data.author).first() comment_candidate = form.comment.data comment = Comments(body=comment_candidate, video_id=data.id, user_id=user.id) db.session.add(comment) db.session.commit() msg = "Comment added!" return render_template('video.html', video=data, form=form, msg=msg) if data: return render_template('video.html', video=data, form=form) else: msg = "No video found!" return render_template('video.html', msg=msg)
def add_comment(post_id): from models import Comment from forms import CommentForm comment = CommentForm(request.form) # # if not Post.query.get(post_id): # КАК СДЕЛАТЬ ВАЛИДАТОР ПО ЛЮДСКИ?? # flash('No such Post! Nothing to comment') # return render_template('flash_page.html'), 403 if comment.validate(): comment = Comment(**comment.data) comment.post_id = post_id db.session.add(comment) db.session.commit() flash('A very good Comment was added for Post number {}'.format(comment.post_id)) return render_template('flash_page.html'), 200 else: flash('Something wrong! {}'.format(str(comment.errors))) return render_template('flash_page.html'), 403
def comment_post(): from models import Comment from forms import CommentForm if request.method == 'POST': print(request.form) form = CommentForm(request.form) if form.validate(): print("Validated") comment = Comment(**form.data) db.session.add(comment) db.session.commit() flash('Comment posted!') else: flash('Form is not valid! Post was not created.') flash(str(form.errors)) return 'OK'
def post_page(postid): post = get_post(postid) if not post: flash("Post does not exist.") return redirect(url_for('error')) page = get_page(postid) # page post belongs to # Check whether post/comment thread rooted off a personal page or group page. if page.pagetype == 'Group': if not in_group(session['userid'], page.groupid): flash("You can't view this page without joining the group.") return redirect(url_for('group_error', groupid=page.groupid)) group = get_group(page.groupid) origin_type = 'group' else: user = userid_to_object(page.ownerid) origin_type = 'user' form = CommentForm(request.form) # write a comment if form.validate() and request.method == 'POST': comment_on_post(postid, session['userid'], form.content.data) redirect(url_for('post_page', postid=postid)) form = CommentForm() post = get_post(postid) #debug for c in post.comments: print(c.content, c.likes) # if origin_type == 'user': return render_template('pages/post.html', form=form, post=post, user=user, group=None) else: return render_template('pages/post.html', form=form, post=post, group=group, user=None)
def comment(post_id=None): """ Creates a comment for a blog post. GET - Displays comment form if user is logged in. POST - Writes comment to database. """ form = CommentForm(request.form) post = g.db_session.query(Post).filter_by(id=post_id).first() if request.method == 'POST' and form.validate(): comment = Comment(form.content.data, current_user.get_id(), post.id) g.db_session.add(comment) return redirect(url_for('blog.view_post', post_id=post_id)) try: return render_template('comment_new.html', form=form, post=post) except TemplateNotFound: abort(404)
class CommentFormProcessor(FormProcessor): def __init__(self, *args, **kwargs): super(CommentFormProcessor, self).__init__(*args, **kwargs) self.select_form() def select_form(self): if self.page.form: self.form = self.page.form self.form = self.process_form() else: self.get_form() self.form_template = "comment_form.html" self.rendered_form = self.render_form() def get_form(self): self.form = CommentForm() def process_form(self): if self.form.validate_on_submit() or self.form.validate(): # eastern = pytz.timezone('America/New_York') # current_time = datetime.now(eastern).isoformat() current_time = datetime.utcnow() comment = Comment(comment=self.form.comment.data, post_id=self.page.post_id, user_id=current_user.id, created_at=current_time) db.session.add(comment) db.session.commit() if request.is_xhr: response = comment.json_view() response['savedsuccess'] = True self.rendered_form = response else: self.form = None self.rendered_form = None else: if request.is_xhr: self.form.errors['iserror'] = True return json.dumps(self.form.errors) else: self.template = "post_form.html" self.form_template = self.get_form_template() self.rendered_form = self.render_form()
def create(article_id): from models import Comment, Article from forms import CommentForm article = Article.query.filter_by(id=article_id).first() if request.method == 'POST': form = CommentForm(request.form) if form.validate(): data = Comment(**form.data) db.session.add(data) db.session.commit() data.comment_id = article.id db.session.commit() return redirect(url_for('create', article_id=article_id)) else: return redirect(url_for('create', article_id=article_id)) if request.method == 'GET': all_comments = Comment.query.filter_by(comment_id=article_id) return render_template('article.html', article=article, comments=all_comments, date_today=date.today())
def project_index(proj_id): form = CommentForm(request.form) mess = MessageForm(request.form) proj = db.session.query(Projects).filter_by(id=proj_id).first() if proj is None: abort(404) css=True if g.user in proj.get_users(): css=False if request.method == 'POST' and form.validate(): comm = Comments(form.comment.data, g.user, proj) db.session.add(comm) db.session.commit() flash('Comment added') #td change anchor in v0.9 return redirect('projects/%s#2' % proj_id) #app.logger.debug(proj.get_users()) return render_template('project.html', query=proj, form=form, mess=mess, css=css)
def viewsession(name, slug): space = ProposalSpace.query.filter_by(name=name).first() if not space: abort(404) try: proposal_id = int(slug.split('-')[0]) except ValueError: abort(404) proposal = Proposal.query.get(proposal_id) if not proposal: abort(404) if proposal.proposal_space != space: return redirect(url_for('viewsession', name=proposal.proposal_space.name, slug=proposal.urlname), code=301) if slug != proposal.urlname: return redirect(url_for('viewsession', name=proposal.proposal_space.name, slug=proposal.urlname), code=301) # URL is okay. Show the proposal. comments = sorted(Comment.query.filter_by(commentspace=proposal.comments, parent=None).order_by('created_at').all(), key=lambda c: c.votes.count, reverse=True) commentform = CommentForm() delcommentform = DeleteCommentForm() if request.method == 'POST': if request.form.get('form.id') == 'newcomment' and commentform.validate(): if commentform.edit_id.data: comment = Comment.query.get(int(commentform.edit_id.data)) if comment: if comment.user == g.user: comment.message = commentform.message.data comment.message_html = markdown(comment.message) comment.edited_at = datetime.utcnow() flash("Your comment has been edited", "info") else: flash("You can only edit your own comments", "info") else: flash("No such comment", "error") else: comment = Comment(user=g.user, commentspace=proposal.comments, message=commentform.message.data) if commentform.parent_id.data: parent = Comment.query.get(int(commentform.parent_id.data)) if parent and parent.commentspace == proposal.comments: comment.parent = parent comment.message_html = markdown(comment.message) proposal.comments.count += 1 comment.votes.vote(g.user) # Vote for your own comment db.session.add(comment) flash("Your comment has been posted", "info") db.session.commit() # Redirect despite this being the same page because HTTP 303 is required to not break # the browser Back button return redirect(url_for('viewsession', name=space.name, slug=proposal.urlname) + "#c" + str(comment.id), code=303) elif request.form.get('form.id') == 'delcomment' and delcommentform.validate(): comment = Comment.query.get(int(delcommentform.comment_id.data)) if comment: if comment.user == g.user: comment.delete() proposal.comments.count -= 1 db.session.commit() flash("Your comment was deleted.", "info") else: flash("You did not post that comment.", "error") else: flash("No such comment.", "error") return redirect(url_for('viewsession', name=space.name, slug=proposal.urlname), code=303) return render_template('proposal.html', space=space, proposal=proposal, comments=comments, commentform=commentform, delcommentform=delcommentform, breadcrumbs=[(url_for('viewspace', name=space.name), space.title)])
def viewsession(name, slug): space = ProposalSpace.query.filter_by(name=name).first() if not space: abort(404) try: proposal_id = int(slug.split('-')[0]) except ValueError: abort(404) proposal = Proposal.query.get(proposal_id) if not proposal: abort(404) if proposal.proposal_space != space: return redirect(url_for('viewsession', name=proposal.proposal_space.name, slug=proposal.urlname), code=301) if slug != proposal.urlname: return redirect(url_for('viewsession', name=proposal.proposal_space.name, slug=proposal.urlname), code=301) # URL is okay. Show the proposal. comments = sorted( Comment.query.filter_by(commentspace=proposal.comments, parent=None).order_by('created_at').all(), key=lambda c: c.votes.count, reverse=True) commentform = CommentForm() commentform.message.flags.markdown = True delcommentform = DeleteCommentForm() if request.method == 'POST': if request.form.get( 'form.id') == 'newcomment' and commentform.validate(): send_mail_info = [] if commentform.edit_id.data: comment = Comment.query.get(int(commentform.edit_id.data)) if comment: if comment.user == g.user: comment.message = commentform.message.data comment.message_html = markdown(comment.message) comment.edited_at = datetime.utcnow() flash("Your comment has been edited", "info") else: flash("You can only edit your own comments", "info") else: flash("No such comment", "error") else: comment = Comment(user=g.user, commentspace=proposal.comments, message=commentform.message.data) if commentform.parent_id.data: parent = Comment.query.get(int(commentform.parent_id.data)) if parent.user.email: if parent.user == proposal.user: # check if parent comment & proposal owner are same if not g.user == parent.user: # check if parent comment is by proposal owner send_mail_info.append({ 'to': proposal.user.email or proposal.email, 'subject': "%s Funnel:%s" % (name, proposal.title), 'template': 'proposal_comment_reply_email.md' }) else: # send mail to parent comment owner & proposal owner if not parent.user == g.user: send_mail_info.append({ 'to': parent.user.email, 'subject': "%s Funnel:%s" % (name, proposal.title), 'template': 'proposal_comment_to_proposer_email.md' }) if not proposal.user == g.user: send_mail_info.append({ 'to': proposal.user.email or proposal.email, 'subject': "%s Funnel:%s" % (name, proposal.title), 'template': 'proposal_comment_email.md' }) if parent and parent.commentspace == proposal.comments: comment.parent = parent else: # for top level comment if not proposal.user == g.user: send_mail_info.append({ 'to': proposal.user.email or proposal.email, 'subject': "%s Funnel:%s" % (name, proposal.title), 'template': 'proposal_comment_email.md' }) comment.message_html = markdown(comment.message) proposal.comments.count += 1 comment.votes.vote(g.user) # Vote for your own comment db.session.add(comment) flash("Your comment has been posted", "info") send_comment_mail(proposal, comment) db.session.commit() to_redirect = url_for('viewsession', name=space.name, slug=proposal.urlname, _external=True) + "#c" + str(comment.id) for item in send_mail_info: email_body = render_template(item.pop('template'), proposal=proposal, comment=comment, link=to_redirect) send_mail(sender=None, body=email_body, **item) # Redirect despite this being the same page because HTTP 303 is required to not break # the browser Back button return redirect(to_redirect, code=303) elif request.form.get( 'form.id') == 'delcomment' and delcommentform.validate(): comment = Comment.query.get(int(delcommentform.comment_id.data)) if comment: if comment.user == g.user: comment.delete() proposal.comments.count -= 1 db.session.commit() flash("Your comment was deleted.", "info") else: flash("You did not post that comment.", "error") else: flash("No such comment.", "error") return redirect(url_for('viewsession', name=space.name, slug=proposal.urlname), code=303) links = [ Markup(url_re.sub(urllink, unicode(escape(l)))) for l in proposal.links.replace('\r\n', '\n').split('\n') if l ] confirmform = ConfirmSessionForm() return render_template('proposal.html', space=space, proposal=proposal, comments=comments, commentform=commentform, delcommentform=delcommentform, breadcrumbs=[(url_for('viewspace', name=space.name), space.title)], links=links, confirmform=confirmform)
def viewsession(name, slug): space = ProposalSpace.query.filter_by(name=name).first() if not space: abort(404) try: proposal_id = int(slug.split('-')[0]) except ValueError: abort(404) proposal = Proposal.query.get(proposal_id) if not proposal: abort(404) if proposal.proposal_space != space: return redirect(url_for('viewsession', name=proposal.proposal_space.name, slug=proposal.urlname), code=301) if slug != proposal.urlname: return redirect(url_for('viewsession', name=proposal.proposal_space.name, slug=proposal.urlname), code=301) # URL is okay. Show the proposal. comments = sorted(Comment.query.filter_by(commentspace=proposal.comments, parent=None).order_by('created_at').all(), key=lambda c: c.votes.count, reverse=True) commentform = CommentForm() commentform.message.flags.markdown = True delcommentform = DeleteCommentForm() if request.method == 'POST': if request.form.get('form.id') == 'newcomment' and commentform.validate(): send_mail_info = [] if commentform.edit_id.data: comment = Comment.query.get(int(commentform.edit_id.data)) if comment: if comment.user == g.user: comment.message = commentform.message.data comment.message_html = markdown(comment.message) comment.edited_at = datetime.utcnow() flash("Your comment has been edited", "info") else: flash("You can only edit your own comments", "info") else: flash("No such comment", "error") else: comment = Comment(user=g.user, commentspace=proposal.comments, message=commentform.message.data) if commentform.parent_id.data: parent = Comment.query.get(int(commentform.parent_id.data)) if parent.user.email: if parent.user == proposal.user: # check if parent comment & proposal owner are same if not g.user == parent.user: # check if parent comment is by proposal owner send_mail_info.append({'to': proposal.user.email or proposal.email, 'subject': "%s Funnel:%s" % (name, proposal.title), 'template': 'proposal_comment_reply_email.md'}) else: # send mail to parent comment owner & proposal owner if not parent.user == g.user: send_mail_info.append({'to': parent.user.email, 'subject': "%s Funnel:%s" % (name, proposal.title), 'template': 'proposal_comment_to_proposer_email.md'}) if not proposal.user == g.user: send_mail_info.append({'to': proposal.user.email or proposal.email, 'subject': "%s Funnel:%s" % (name, proposal.title), 'template': 'proposal_comment_email.md'}) if parent and parent.commentspace == proposal.comments: comment.parent = parent else: # for top level comment if not proposal.user == g.user: send_mail_info.append({'to': proposal.user.email or proposal.email, 'subject': "%s Funnel:%s" % (name, proposal.title), 'template': 'proposal_comment_email.md'}) comment.message_html = markdown(comment.message) proposal.comments.count += 1 comment.votes.vote(g.user) # Vote for your own comment db.session.add(comment) flash("Your comment has been posted", "info") db.session.commit() to_redirect = url_for('viewsession', name=space.name, slug=proposal.urlname, _external=True) + "#c" + str(comment.id) for item in send_mail_info: email_body = render_template(item.pop('template'), proposal=proposal, comment=comment, link=to_redirect) send_mail(sender=None, body=email_body, **item) # Redirect despite this being the same page because HTTP 303 is required to not break # the browser Back button return redirect(to_redirect, code=303) elif request.form.get('form.id') == 'delcomment' and delcommentform.validate(): comment = Comment.query.get(int(delcommentform.comment_id.data)) if comment: if comment.user == g.user: comment.delete() proposal.comments.count -= 1 db.session.commit() flash("Your comment was deleted.", "info") else: flash("You did not post that comment.", "error") else: flash("No such comment.", "error") return redirect(url_for('viewsession', name=space.name, slug=proposal.urlname), code=303) links = [Markup(url_re.sub(urllink, unicode(escape(l)))) for l in proposal.links.replace('\r\n', '\n').split('\n') if l] confirmform = ConfirmSessionForm() return render_template('proposal.html', space=space, proposal=proposal, comments=comments, commentform=commentform, delcommentform=delcommentform, breadcrumbs=[(url_for('viewspace', name=space.name), space.title)], links=links, confirmform=confirmform)