def create_comment_answer(request, answer_id): a = Answer.objects.get(id=answer_id) if request.POST: f = CommentForm(request.POST) if f.is_valid(): c = f.save(commit=False) c.pub_date = timezone.now() c.related_answer = a c.posted_by = request.user c.save() a.num_comments += 1 a.comments.add(c) a.save() return HttpResponseRedirect('/get/%s' % a.related_article_id) else: f = CommentForm() args = {} args.update(csrf(request)) args['article'] = a args['form'] = f return render(request, 'add_comment.html', args)
def article(request, context, article_id): context.update(csrf(request)) context["article"] = Article.objects.get(id=article_id) context["commnets"] = Comment.objects.filter(article=article_id) # article_id) if True: # context['userAuthenticated']:#see frontEnd decorator ################################# # check commment create: if "commentButton" in request.POST: # comment(create) button clicked! comment_form = CommentForm( request.POST ) # if is valid --> save if not we create a new CommentForm with some error for user(like empty field and ...) if comment_form.is_valid(): writer = context["user"] # see frontEnd decorator body = request.POST["body"] Comment.objects.create(writer=writer, body=body, article=context["article"]) # comment = Comment.objects.create(writer=writer,body=body,article=article) return HttpResponseRedirect("") # just for reload the page and cleaning the fields else: comment_form = CommentForm() # create a simple CommentForm ################################## else: comment_form = None # set template variable: context["comment_form"] = comment_form return render_to_response("frontEnd/article/article.html", context)
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 add_comment(request, article_id): a = Article.objects.get(id=article_id) if request.method == "POST": f = CommentForm(request.POST) if f.is_valid(): # save this frm but do NOT push anything into db c = f.save(commit=False) c.pub_date = timezone.now() # RELATIONSHIP: relate this COMMENT with correcponding ARTICLE c.article = a c.save() return HttpResponseRedirect('/articles/get/%s' % article_id) # if this is not the POST method - so the first time we are seeing this else: f = CommentForm() args = {} args.update(csrf(request)) args['article'] = a args['form'] = f return render_to_response('add_comment.html', args)
def article(request, post_id, post_name): post = Post.posts.get_visible_post(post_id) if not post: raise Http404 if request.method == "POST": comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = Comment() comment.author = comment_form.cleaned_data['author'] comment.post = post comment.email = comment_form.cleaned_data['email'] comment.text = comment_form.cleaned_data['text'] comment.save() return HttpResponseRedirect("/") else: # TODO SHOW ERRORS pass spotlighted = Project.objects.filter(related_posts=post) comments = Comment.objects.filter(post=post) related = TaggedItem.objects.get_related(post, Post)[:6] comment_form = CommentForm() return render_to_response('article.html', { "post": post, "comments": comments, "related": related, "spotlighted": spotlighted, "comment_form": comment_form }, context_instance=RequestContext(request))
def add_comment(request, id): form = CommentForm(request.POST) if form.is_valid(): post = Blog.objects.get(id=id) form.save(post = post) return HttpResponseRedirect('/')
def show_issue(request, related_issue, user_status='group_task_receiver'): # use "filter" to exclude all deleted issues without extra "if" issue = Issue.objects.filter(pk=related_issue).exclude(status = 'deleted')[0] if request.method == 'POST' and 'comment' in request.POST: form = CommentForm(request.POST) if form.is_valid(): cd = form.cleaned_data comment = Comment() comment.add(cd, request.user, issue.id) return HttpResponseRedirect("") elif request.method == 'POST' and 'comment' not in request.POST: status = [key for key in request.POST] issue.renew_status(status[0], request.user) return HttpResponseRedirect("") else: issue.count_comments() issue.define_condition() counter = count_issues(request) comments = comments_gettext_loop(Comment.objects.filter(issue=issue).order_by('date')) if request.user in issue.receiver.all(): user_status = 'receiver' if request.user == issue.author: user_status = 'author' form = CommentForm() return render_to_response('issue_page.html', {'form': form, 'user': request.user, 'issue': issue, 'comments': comments, 'user_status': user_status, 'receivers': issue.receiver.all(), 'counter': counter, })
def coment_sucesso(request, id): form = CommentForm(request.POST or None) if request.method == 'POST' and form.is_valid(): post = Post.objects.get(id=id) print form.cleaned_data['comentario'] comentario = Comentario() comentario.post = post comentario.email = request.POST['email'] comentario.nome = request.POST['nome'] comentario.comentario = form.cleaned_data['comentario'] print comentario.id comentario.save() print comentario.id html = Template("""<a href="{% url 'home' %}">Página inicial</a></br> <h2>Comentario postado com sucesso no post {{id}}</h2> """).render(Context({'id' : id})) return HttpResponse(html) else: post = get_object_or_404(Post, id=id) # Formulário já volta preenchido da view form = CommentForm(request.POST or None) comentarios = Comentario.objects.filter(post=post) return render(request, 'detalhePost.html', {'post' : post, 'comentarios' : comentarios, 'form' : form})
def add_comment(request, article_id): a = Article.objects.get(id=article_id) if request.method == "POST": f = CommentForm(request.POST) if f.is_valid(): c = f.save(commit=False) c.pub_date = timezone.now() c.article = a c.save() messages.success(request, "You Comment was added") return HttpResponseRedirect("/articles/get/%s" % article_id) else: f = CommentForm() args = {} args.update(csrf(request)) args["article"] = a args["form"] = f return render_to_response("add_comment.html", args)
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)
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 add_comment(request, book_id): book = Book.objects.get(id=book_id) if request.POST: f = CommentForm(request.POST) if f.is_valid(): c = f.save(commit=False) c.book = book c.save() return HttpResponseRedirect('/books/book/%s' % books_id) else: f = CommentForm() args = {} args.update(csrf(request)) args['book'] = book args['form'] = f # right box args['menu'] = Menu.objects.all() args['pop_books'] = Book.objects.all().order_by('likes').reverse()[:10] args['new_books'] = Book.objects.all().order_by('date').reverse()[:10] args['cats'] = Category.objects.all() args['tags'] = Tag.objects.all() args['current_item'] = 'книги' # user args['username'] = auth.get_user(request).username # poll args['question_web'] = Question.objects.get(text=u"Как вам наш сайт?") args['choices'] = Choice.objects.filter(question_id=args['question_web'].id) return render_to_response('book/book.html', args)
def show_suggestion(request, suggestion_pk): suggestion = get_object_or_404(Suggestion, pk=suggestion_pk) comments = suggestion.comments.all() if request.method == 'POST' and request.user.is_authenticated(): comment_form = CommentForm(request.POST) if comment_form.is_valid(): instance = comment_form.save(commit=False) instance.comment_by = request.user instance.suggestion = suggestion instance.save() return HttpResponseRedirect(reverse('suggestion_detail', kwargs={'suggestion_pk' : suggestion.pk})) else: comment_form = CommentForm() return render_to_response('sdvapp/suggestion_detail.html', {'suggestion' : suggestion, 'comments' : comments, 'comment_form' : comment_form,}, context_instance=RequestContext(request))
def add_comment(request, article_id): a = Article.objects.get(id=article_id) if request.method == "POST": f = CommentForm(request.POST) if f.is_valid(): c = f.save(commit=False) c.pub_date = timezone.now() c.article = a c.approved = False codes = random_code() + format(timezone.now(), u'U') c.code = codes c.save() message = c.name + " commented on your article: " + c.article.title + "<br><br>" + c.body message = message + "<br><br><br><br>Follow this link to approve<br><a href='http://127.0.0.1:8000/articles/approvecom/" + codes + "/'>http://127.0.0.1:8000/articles/approvecom/" + codes + "/</a><br><br>" message = message + "<br><br>Follow this link to delete<br><a href='http://127.0.0.1:8000/articles/deletecom/" + codes + "/'>http://127.0.0.1:8000/articles/deletecom/" + codes + "/</a>" msg = EmailMessage('Comment needs approval', message, '*****@*****.**', ['*****@*****.**']) msg.content_subtype = "html" msg.send() return HttpResponseRedirect('/articles/get/%s' % article_id) else: f = CommentForm() args = {} args.update(csrf(request)) args['article'] = a args['form'] = f return render_to_response('add_comment.html', args)
def blog_detail(request, slug): user = request.user SLUGS = [ 'slug', 'drupal_slug', 'nid', 'id', ] for slug_name in SLUGS: try: if 'id' not in slug_name or slug.isdigit(): content = Blog.objects.get(**{slug_name: slug}) break except Blog.DoesNotExist: continue else: raise Http404 comments = Comment.objects.filter(blog=content).order_by('-create_time') contents = {'content': content, 'comments': comments} contents.update(csrf(request)) if request.method == 'POST' and user.is_authenticated(): comment_form = CommentForm(request.POST) if comment_form.is_valid(): ip = request.META['REMOTE_ADDR'] comment_form.save(content, user, ip) return redirect(request.META['HTTP_REFERER']) else: comment_form = CommentForm() contents['comment_form'] = comment_form return render(request, 'blog/blog_detail.html', contents)
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 post(self, request, slug): product = get_object_or_404(Product, slug=slug) like = True if request.user.is_authenticated(): like = Likes.objects.filter(user=request.user, product=product).exists() comments = Comment.objects.filter(product=product, pub_date__range=[ t.now() - t.timedelta(hours=24), t.now() ]).values('name', 'comment') form = CommentForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your comment has been added!') return redirect(reverse('test_task:product_detail', args=[product.slug])) else: messages.error(request, 'Your comment is not added.') context = {'product': product, 'comments': comments, 'form': form, 'like': like} return render(request, 'test_task/product_detail.html', context)
def comment(request, slug): post = BlogPost.objects.get(slug=slug) if not post.allowcomments: raise PermissionDenied('This post does not allow comments.') if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): data = form.cleaned_data comment = BlogPostComment() comment.blogpost = post comment.authorname = data['name'] comment.authoremail = data['email'] comment.authorurl = data['url'] comment.content = data['content'] comment.approved = not __isCommentSpam(comment) comment.save() return HttpResponseRedirect(post.get_absolute_url()) else: # TODO: handle this assert(False) else: raise PermissionDenied('Method not supported')
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)
def home(request): blog_posts = load_blog() results = [] archieves = [] for blog in blog_posts: body = blog.body new_list = [m.start() for m in re.finditer(r"<br />",body)] new_line = body.index('<br />') for item in new_list: if item >= 750: new_line = item break; body = body[:new_line] pre_start_list = [m.start() for m in re.finditer(r"<pre ",body)] pre_end_list = [m.start() for m in re.finditer(r"</pre>",body)] if pre_start_list: if not pre_end_list: pre_end = [m.start() for m in re.finditer(r"</pre>",blog.body)][0] body = blog.body[:pre_end] archieves.append(blog.title) date = blog.day[:10] day = date[8:10] month = date[5:7] mnth = get_month(month) results.append({'day': day, 'month': mnth, 'body': body, 'title': blog.title}) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): data = form.cleaned_data p = Comments(name=data['name'], comment=data['comment'], title=request.POST['post_title']) p.save() comments = Comments.objects.order_by("-id") return render(request, 'home.html', {'posts': results, 'outline': archieves, 'comments': comments, 'form':CommentForm})
def comment(request): if request.is_ajax(): form = CommentForm(request.POST) if form.is_valid(): blog_id = request.GET.get('blog_id') blog = get_object_or_404(Blog, pk=blog_id) blog.comment_num += 1 blog.save() # pre_comid = form.cleaned_data['pre_comid'] nickname = form.cleaned_data['anickname'] email = form.cleaned_data['bemail'] website = form.cleaned_data['cwebsite'] content = form.cleaned_data['dcontent'] photo = str(random.randint(0, 9)) + '.png' u = User(name=nickname, email=email, website=website, photo=photo) u.save() c = Comment(user=u, blog=blog, content=content, comment_time=timezone.now()) c.save() # sendCommentReply(email) # SendEmail_Comment(nickname,None) return ResponseMsg(True, u'谢谢你的评论') else: return ResponseMsg(False, form.errors.popitem()[1]) else: raise Http404
def add_comment(request, person_id): a = Persons.objects.get(id=person_id) if request.method == "POST": f = CommentForm(request.POST) if f.is_valid(): c = f.save(commit=False) c.CreatedOn = timezone.now() c.person = a c.save() messages.success(request, "Your comment was added") return HttpResponseRedirect('/persons/get/%s' % person_id) else: f = CommentForm() args = {} args.update(csrf(request)) args['person'] = a args['form'] = f return render_to_response('add_comment.html', args) message.add_message(request, settings.DELETE_MESSAGE, "Your comment was deleted successfully") return HttpResponseRedirect('/persons/get/%s' % person_id)
def edit_post(request, pk_thread=None, pk_post=None): """Edit a thread.""" post = get_object_or_404(Post, pk=pk_post) thread = get_object_or_404(Thread, pk=pk_thread) forum = Forum.objects.get(thread__pk=pk_thread) is_admin = False club = Club.objects.get(forum=forum) student = StudentProfile.objects.get(user=request.user) if Member.objects.filter(club=club, student__user=request.user, admin=True): is_admin = True if pk_post: post = get_object_or_404(Post, pk=pk_post) if post.creator != request.user and is_admin == False: raise Http404 else: post = Post(creator=request.user) if request.POST: form = CommentForm(request.POST, instance=post) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("forum.views.thread", args=[pk_thread]) + "?page=last") else: form = CommentForm(instance=post) return render_to_response('forum/post_edit.html', add_csrf(request, form=form), context_instance=RequestContext(request))
def add_comment(request, article_id): print article_id a = Article.objects.get(id=article_id) values = {} values.update(csrf(request)) values['form'] = CommentForm() values['article'] = a page = render_to_response("add_comment.html", values) print "Checking whether a form was submitted" print request.method if request.method == 'POST': print "Form submitted" f = CommentForm(request.POST) if f.is_valid(): print "Form is valid" c = f.save(commit=False) c.pub_date = timezone.now() c.article = a c.save() page = HttpResponseRedirect('/articles/get/%s' % article_id) return page
def post(self, request, *args, **kwargs): user = request.user restaurant = Restaurant.objects.get(pk=kwargs['pk']) comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.restaurant = restaurant comment.time = datetime.datetime.now() comment.buyer =request.user comment.save() comment_form = CommentForm() address = Address.objects.get(restaurant=restaurant) dishesObject = Dish.objects.filter(restaurant=restaurant) dishes = dishesObject.extra( select={'total_like': 'liked/(liked+unliked)'}, order_by=['-total_like'] )[:3] comment = list(Comment_R.objects.filter(restaurant=restaurant).order_by('-time')) ratetotal = Comment_R.objects.filter(restaurant=restaurant) ratecount = ratetotal.count() temp = 0 for r in ratetotal: temp = temp + r.rating if ratecount == 0: rate = 0 else: rate = temp / ratecount return render(request, self.template, {'NavSearchForm':NavSearchForm, 'restaurant': restaurant, 'address': address, 'dishes': dishes, 'dishcount': dishesObject.count(), 'comment': comment, 'comment_form': comment_form, 'rate': round(rate,1), 'ratecount': ratecount})
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)
def add(request): redirect_to=COMMENT_REDIRECT_TO if request.POST: form=CommentForm(request.POST) if form.is_valid(): if 'redirect' in form.cleaned_data: redirect_to=form.cleaned_data['redirect'] else: redirect_to=COMMENT_REDIRECT_TO if not request.user.is_authenticated(): msg = _("In order to post a comment you should have a friendsnippets account.") msg = urlquote_plus(msg) if COMMENT_SIGNIN_VIEW: redirect_to=reverse(COMMENT_SIGNIN_VIEW) + "?next=" + redirect_to + "&msg=" + msg else: redirect_to='/' if not request.user.is_authenticated(): return HttpResponseRedirect(redirect_to) try: content_type=ContentType.objects.get(id=form.cleaned_data['content_type']) except: pass if content_type: params = { 'headline':form.cleaned_data['headline'], 'comment':form.cleaned_data['comment'], 'user':request.user, 'content_type':content_type, 'object_id':form.cleaned_data['object_id'], } c = Comment(**params) c.save() return HttpResponseRedirect(redirect_to)
def post_comments(request, year, month, slug): context = dict() context.update(csrf(request)) now = datetime.datetime.now() if year and month and slug: post = Post.objects.get(created__year=int(year), created__month=int(month), slug=slug) form = CommentForm(request.POST or None) if request.method == 'POST': if form.is_valid(): comment = form.save(commit=False) u = User.objects.get(username=request.user.username) comment.author = u comment.created = now comment.post = post comment.save() form = CommentForm() #TODO maybe should got to blog/year/month/slug #return HttpResponseRedirect('/blog%s' % post.get_absolute_url()) comments = Comment.objects.filter(post=post).order_by("-created") context['post'] = post context['comments'] = comments context['form'] = form return render(request, 'post_comments.html', context)
def add_comment(request, event_id): e = Event.objects.get(id=event_id) if request.method == "POST": f = CommentForm(request.POST) if f.is_valid(): user_logger.debug('COMMENTED: '+request.user.username+' to '+event_id) c = f.save(commit=False) c.pub_date = timezone.now() c.username = request.user.username c.event = e c.save() return HttpResponseRedirect('/events/get/%s' % event_id) else: f = CommentForm() args = {} args.update(csrf(request)) args['event'] = e args['form'] = f return render_to_response('listing.html', args, context_instance=RequestContext(request))
def service_comments(request, id): service = get_object_or_404(Service, id=id) if not service.is_active(): raise Http404 # check if user is allowed to comment if request.user.is_authenticated(): now = datetime.datetime.now() reservations = Reservation.objects.filter(Q(user=request.user, service=service) & (Q(date__lt=now.date()) | Q(date=now.date(), time__lt=now.time()))).order_by('-date', '-time') if len(reservations) and not Comment.objects.filter(author=request.user, service=service, created__gt=datetime.datetime.combine(reservations[0].date, reservations[0].time)).exists(): # handle form if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.service = service comment.author = request.user comment.save() return HttpResponseRedirect(reverse(service_comments, args=(id,))) else: form = CommentForm() # get all comments comments = service.comments.order_by('-created').all() return render_to_response('service/comments.html', locals(), context_instance=RequestContext(request))
def show_post(post_id): requested_post = BlogPost.query.get(post_id) comment_form = CommentForm() if comment_form.validate_on_submit(): if not current_user.is_authenticated: flash('you have got to login, bucko. to make a post') return redirect(url_for('login')) text = comment_form.body.data new_comment = Comment(text=text, blog=requested_post, commenter=current_user) db.session.add(new_comment) db.session.commit() return render_template("post.html", post=requested_post, user=current_user, comment_form=comment_form) return render_template("post.html", post=requested_post, user=current_user, comment_form=comment_form)
def delete_comment(post_id, comment_id): comment_to_delete = Comment.query.get(comment_id) db.session.delete(comment_to_delete) db.session.commit() form = CommentForm() requested_post = BlogPost.query.get(post_id) return render_template("post.html", post=requested_post, form=form, current_user=current_user)
def add_comment(request, article_id): a = Article.objects.get(id=article_id) if request.method == "POST": f = CommentForm(request.POST) if f.is_valid(): c = f.save(commit=False) c.pub_date = timezone.now() c.article = a c.save() messages.success(request, "You Comment was added") return HttpResponseRedirect('/articles/get/%s' % article_id) else: f = CommentForm() args = {} args.update(csrf(request)) args['article'] = a args['form'] = f return render_to_response('add_comment.html', args)
def add(request): user = request.user if request.method == 'GET': initial = {} if user.is_authenticated(): try: profile = request.user.get_profile() except: profile = None initial['username'] = '******'.join([ name for name in user.last_name, user.first_name, getattr(profile, 'middle_name', '') if name ]) if not initial['username']: initial['username'] = request.user.username initial['email'] = request.user.email initial['base_object'] = request.GET.get('bid') initial['re'] = request.GET.get('re') form = CommentForm(initial=initial) else: data = dict([(key, value.strip()) for key, value in request.POST.items()]) form = CommentForm(data) if form.is_valid(): comment = form.save() if user.is_authenticated(): comment.author = user comment.save() return u"Спасибо за Ваш комментарий! После рассмотрения модератором он будет опубликован!<p><a href=''>Обновить страницу</a></p>" context = {'form': form} return template_loader.get_template("tsogu_comments_form.html").render( RequestContext(request, context))
def paste_view(request, pk): paste_set = get_object_or_404(Set, pk=pk) requested_commit = request.GET.get('commit') # Meh, this could be done better and I am a bit disappointed that you # can't filter on the request.user if it is AnonymousUser, so we have # to do this request.user.is_authenticated() favorited = False if request.user.is_authenticated(): favorited = Favorite.objects.filter(parent_set=paste_set, user=request.user).exists() # A requested commit allows us to navigate in history latest_commit = paste_set.commit_set.latest('created') if requested_commit is None: commit = latest_commit else: commit = get_object_or_404(Commit, parent_set=paste_set, commit=requested_commit) if request.method != 'POST': comment_form = CommentForm() else: comment_form = CommentForm(request.POST) if comment_form.is_valid() and request.user.is_authenticated(): comment = Comment.objects.create( commit=commit, owner=request.user, comment=comment_form.cleaned_data['comment']) return render_to_response( 'paste_view.html', { 'paste_set': paste_set, 'pastes': commit.paste_set.all().order_by('id'), 'commit_current': commit, 'favorited': favorited, 'editable': latest_commit == commit, 'comment_form': comment_form }, RequestContext(request))
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 view_post(post_id): post = session.query(Post).filter_by(id=post_id).one() creator = session.query(User).filter_by(id=post.user_id).one() blog = session.query(Blog).filter_by(user_id=creator.id).one() comments = session.query(Comment).filter_by(post_id=post_id).order_by( Comment.commented_ts).all() if request.method == 'POST': login_session.pop('_flashes', None) # user cannot like the same post more than one time. If one tries to, # it raises integrity error (unique constraint failed) if request.form['submit'] == "Like it": try: like = Likes(user_id=login_session['user_id'], post_id=post_id) session.add(like) session.flush() except exc.IntegrityError: session.rollback() flash("You already liked this post") else: post.likes += 1 session.add(post) session.commit() return redirect('/') else: # private post is only open to the creator itself if post.publish == 'no' and creator.id != login_session.get('user_id'): flash('This post is private') return redirect('/') if 'username' not in login_session: return render_template("view_post.html", post=post, comments=comments, blog=blog, user_id=login_session.get('user_id'), username=login_session.get('username')) if creator.id == login_session.get('user_id'): return render_template("view_post.html", post=post, comments=comments, blog=blog, user_id=login_session.get('user_id'), username=login_session.get('username')) else: form = CommentForm() return render_template("view_post.html", post=post, form=form, comments=comments, blog=blog, user_id=login_session.get('user_id'), username=login_session.get('username'))
def show_post(post_id): post = Post.query.get_or_404(post_id) page = request.args.get('page', 1, type=int) per_page = current_app.config['CLEARLOG_COMMENT_PER_PAGE'] pagination = Comment.query.with_parent(post).filter_by( reviewed=True).order_by(Comment.timestamp.asc()).paginate( page, per_page) comments = pagination.items if current_user.is_authenticated: form = AdminCommentForm() form.author.data = current_user.name form.email.data = current_app.config['CLEARLOG_EMAIL'] form.site.data = url_for('.index') from_admin = True reviewed = True else: form = CommentForm() from_admin = False reviewed = False if form.validate_on_submit(): author = form.author.data email = form.email.data site = form.site.data body = form.body.data comment = Comment(author=author, email=email, site=site, body=body, from_admin=from_admin, post=post, reviewed=reviewed) replied_id = request.args.get('reply') if replied_id: replied_comment = Comment.query.get_or_404(replied_id) comment.replied = replied_comment db.session.add(comment) db.session.commit() if current_user.is_authenticated: # send message based on authentication status flash('Comment published.', 'success') else: flash('Thanks, your comment will be published after reviewed.', 'info') return redirect(url_for('.show_post', post_id=post_id)) return render_template('blog/post.html', post=post, pagination=pagination, form=form, comments=comments)
def remove_comment_from_list(request, storyID, commentID): story = mdl_story.get_story(storyID) comment = mdl_comment.get_comment(commentID) if request.method == 'POST': comment.delete() story.last_updated = datetime.datetime.now() story.save() comments = mdl_comment.get_comments_for_story(story) form = CommentForm() context = {'story': story, 'comments': comments, 'newform': form} return render(request, 'CommentList.html', context)
def article(request, article_id=1): article = Article.objects.get(id=article_id) #adds comment form to article page args = {} args.update(csrf(request)) args['topPosts'] = getTopPosts(5) args['latestPosts'] = getLatest(5) args['answer_form'] = AnswerForm() args['comment_form'] = CommentForm() args['user'] = request.user args['article'] = article return render(request, 'article.html', args)
def show_post(post_id): requested_post = BlogPost.query.get(post_id) list_comments = requested_post.comments form = CommentForm() if form.validate_on_submit(): if not current_user.is_authenticated: flash("You cannot comment.\nYou are not logged in.", category="error") return redirect(url_for("login")) print(requested_post, current_user) new_comment = Comment( body=form.body.data, post=requested_post, commenter=current_user, date=date.today().strftime("%d/%b/%Y"), ) db.session.add(new_comment) db.session.commit() return render_template("post.html", post=requested_post, form=form, comments=list_comments)
def add_comment(request, app, object_id, unique_id): if request.method == 'POST': try: mod = __import__('everes_%s' % app, {}, {}, []) except NameError: raise Http404() form = CommentForm(request.POST) if form.is_valid(): app_dict = getattr(mod, 'APP_DICT') data = get_object_or_404(app_dict.get('queryset'), pk=object_id) uid = get_object_or_404(UniqueId.public_objects.all(), uniqueId=unique_id) uid.valid = False uid.save() comment = form.save(commit=False) comment.contents = data comment.save() return HttpResponseRedirect(data.get_absolute_url()) #TODO なんとかしてdetailにformを渡して返す raise NotImplementedError else: raise Http404
def show_post(post_id): form = CommentForm() if request.method == "POST" and form.validate_on_submit(): if current_user.is_authenticated: body = request.form.get('comment') new_comment = Comment( text=body, author_id=current_user.id, parent_post_id=post_id ) db.session.add(new_comment) db.session.commit() return redirect(url_for('show_post', post_id=post_id)) else: flash('You need to login or register to add a comment') return redirect(url_for('login')) requested_post = BlogPost.query.get(post_id) return render_template("post.html", post=requested_post, current_user=current_user, form=form, gravatar=gravatar)
def comment(event_id, student_id): check_admin() attendance = Attendance.query.get([event_id, student_id]) form = CommentForm(obj=attendance) if form.validate_on_submit(): attendance.is_attended = form.is_attended.data attendance.TF_comment = form.TF_comment.data db.session.commit() flash('You have successfully commented this awesome student.') # redirect to the events page return redirect(url_for('teaching_fellow.detail_event', id=event_id)) form.is_attended.data = attendance.is_attended form.TF_comment.data = attendance.TF_comment return render_template('teaching_fellow/events/comment.html', form=form, name=attendance.student.name, title=attendance.student.name)
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)
def post(id): """ post detail详情页 :param id: :return: """ post = Post.query.get_or_404(id) #根据model的id查出文章的对象 #评论窗体 form = CommentForm() #保存评论 #post方法路由到这里 if form.validate_on_submit(): #post请求,说明有一条新增 或是修改此时根据 comment = Comment(body=form.body.data, post_id=post.id) db.session.add(comment) db.session.commit() #评论列表 return render_template("posts/detail.html", title=post.title, form=form, post=post)
def comment_post(post_id): form = CommentForm() post = session.query(Post).filter_by(id=post_id).one() if 'username' not in login_session: flash('You need to login first to leave a comment') return redirect('/login') if form.validate_on_submit(): comment = Comment(post_id=post_id, commented_ts=time(), commenter=login_session['username'], comment_body=form.comment.data) comment.commented_dt = datetime.utcfromtimestamp( comment.commented_ts).strftime('%Y-%m-%d %H:%M:%S') session.add(comment) session.commit() return redirect(url_for('view_post', post_id=post_id)) print form.errors return render_template('view_post.html', post=post, form=form, user_id=login_session.get('user_id'), username=login_session.get('username'))
def show_post(post_id): comment_form = CommentForm() requested_post = BlogPost.query.get(post_id) if comment_form.validate_on_submit() and current_user.is_authenticated: new_comment = Comment( text=comment_form.comment.data, comment_author=current_user, parent_post=requested_post, ) db.session.add(new_comment) db.session.commit() return redirect(url_for("show_post", post_id=requested_post.id)) elif comment_form.validate_on_submit(): flash("You need to login or register to comment") return redirect(url_for("login")) else: pass return render_template("post.html", post=requested_post, current_user=current_user, form=comment_form, gravatar=gravatar)
def show_post(news_id): form = CommentForm() post = News.query.filter_by(id=news_id).first() soup = make_soup(post.link) if post.tag == 'science': content = soup.select_one('.text-article__inside p') body = content.get_text() else: try: body = soup.select_one('.article__text__overview span').string except AttributeError: body = soup.select_one('.article__text p').string post.body = body try: db.session.commit() except IntegrityError: db.session.rollback() if form.validate_on_submit() and request.method == 'POST': if current_user.is_authenticated: text = request.form.get('comment') new_comment = Comment( text=text, parent_post_id=news_id, author_id=current_user.id ) db.session.add(new_comment) db.session.commit() return redirect(url_for('show_post', news_id=news_id)) else: flash('You need to login or register to add a comment') return redirect(url_for('login')) return render_template('post.html', post=post, body=body, form=form, gravatar=gravatar, current_user=current_user)
def show_post(post_id): requested_post = BlogPost.query.get(post_id) form = CommentForm() 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.comment.data, author_id=current_user.id, comment_author=current_user, post_id=post_id, parent_post=requested_post, ) db.session.add(new_comment) db.session.commit() return redirect(url_for("show_post", post_id=post_id, current_user=current_user)) return render_template("post.html", current_user=current_user, post=requested_post, form=form)
def show_post(post_id): form = CommentForm() requested_post = BlogPost.query.get(post_id) comments = requested_post.comments if form.validate_on_submit(): if current_user.is_authenticated: new_comment = Comment(text=form.comment.data, author=current_user, blog=requested_post) db.session.add(new_comment) db.session.commit() return redirect(url_for('show_post', post_id=post_id)) else: flash("Please log-in to be able to comment.") return redirect(url_for('login')) return render_template("post.html", post=requested_post, form=form)
def show_post(post_id): requested_post = BlogPost.query.get(post_id) form = CommentForm() if form.validate_on_submit(): if not current_user.is_authenticated: flash('You are not logged in') return redirect(url_for('login')) new_comment = Comment(text=form.comment_text.data, author=current_user, post=requested_post) 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, current_user=current_user, form=form)
def comment(self, request, postid): ''' make a comment for given post and render ''' # comfirm current user is a member of the group the post belongs to try: # author = the membership whose group has a membership with the post we're looking at comment_author = request.user.membership_set.get( group__membership__post__pk=postid) except: return HttpResponseForbidden() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) # author = the membership whose group has a membership with the post we're looking at comment.author = comment_author try: comment_post = Post.objects.get(pk=postid) except DoesNotExist: return HttpResponseNotFound() comment.post = comment_post comment.save() # is anybody listening? # if so, send new comment to everyone and reset grpid = int(comment_post.author.group.pk) # Send notifications. uid = request.user.id self._send_notifications(uid, grpid, CommentNotification, comment) if grpid in self.group_event: self.group_event[grpid].set(comment) # self.group_event = None del self.group_event[grpid] return render(request, 'group_comment.html', {'comment': comment}) return HttpResponseBadRequest()
def article_detail(request): categorys = r_sidebar(request) #根据id获取文章 articleid = int(request.GET.get('article')) article = models.Article.objects.get(id=articleid) #更新浏览次数 article.hits += 1 #显示文章评论 commentlist = models.Comment.objects.filter(article_id=articleid) #读者对文章进行顶!d=====( ̄▽ ̄*)b或者踩 if request.POST.has_key('good'): article.goods += 1 if request.POST.has_key('bad'): article.bads += 1 #提交评论 if request.POST.has_key('commentsubmit'): formInfo = CommentForm(request.POST) if formInfo.is_valid(): submiterror = 0 comment = formInfo.cleaned_data models.Comment.objects.create(name=comment['name'], content=comment['content'], article=article, email=comment['email']) article.times += 1 else: submiterror = 1 article.save() form = CommentForm() return render_to_response('article_detail.html', locals(), context_instance=RequestContext(request))
def show_post(post_id): userid = 0 requested_post = BlogPost.query.get(post_id) form = CommentForm() if form.validate_on_submit(): if current_user.is_authenticated: userid = current_user.id data = Comment( text=form.comment.data, comment_author=current_user, parent_post=requested_post, ) db.session.add(data) db.session.commit() else: flash("please login to comment the blog") return redirect(url_for('login')) return render_template("post.html", post=requested_post, is_loggedin=current_user.is_authenticated, id=userid, form=form)
def comment(review_id): """Comment on a user's post""" if not g.user: flash("Access unauthorized.", "danger") return redirect("/") form=CommentForm() comment=Comment(user_id=g.user.id, reviews_id=review_id, text=form.text.data) db.session.add(comment) db.session.commit() return redirect("/")
def displayArticle(filename): if 'logged_in' not in session: flash("You Have To Login First To Access This Page..!!") return redirect(url_for('login')) details, article, status, comment = viewArticle(filename) if status == True: return render_template('view.html', form=ReviewForm(), form1=CommentForm(), details=details, article=article, comment=comment) flash(status) return redirect(url_for('home'))
def get_note(note_id): if session.get('user'): my_note = db.session.query(Note).filter_by( id=note_id, user_id=session['user_id']).one() form = CommentForm() return render_template("note.html", note=my_note, user=session['user'], form=form) else: return redirect(url_for('login'))
def show_post(post_id): requested_post = BlogPost.query.get(post_id) all_comments = ["<p>veamos</p>"] form = CommentForm() if form.validate_on_submit(): print(current_user.name) if current_user.is_authenticated: new_comment = Comment( text=form.comment_text.data, parent_post=requested_post, comment_author=current_user ) db.session.add(new_comment) db.session.commit() # all_comments = Comment.query.filter_by(author_id=current_user.id).all() else: flash("I'm sorry, you should log in before leaving a comment") return redirect(url_for('login')) print(all_comments) return render_template("post.html", post=requested_post, form=form)