def comments(request): comments_list = Comment.objects.order_by('-created_at') if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): captcha_response = request.POST.get['g-recaptcha-response'] data = { 'secret': '6LcdyuAUAAAAAGtSgh1HroDq1k6SMMHjX0g8AJ9c', 'response': captcha_response } r = requests.post( 'https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if result['success']: form.save() messages.success(request, 'New comment added with success!') else: messages.error(request, 'Invalid reCAPTCHA. Please try again.') return redirect('comments') else: form = CommentForm() return render(request, 'comments.html', { 'form': form, 'comments': comments_list })
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 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 detail(slug): post = Post.query.filter(and_(Post.is_published == 1), (Post.slug == slug)).first() posts = Post.query.filter(Post.slug != slug).order_by( Post.id.desc()).limit(3) if request.method == 'POST' and current_user.is_authenticated: comment_post = CommentForm(request.form) try: comment = Comment(text=comment_post.text.data) comment.author = current_user db.session.add(comment) post.comments.append(comment) db.session.add(post) db.session.commit() except Exception as exc: db.session.rollback() flash(exc.message, 'danger') print('Error', exc) form = CommentForm() return render_template('posts/detail.html', post=post, tags=enabled_tags, posts=posts, form=form)
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): 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 index2(): from forms import CommentForm form = CommentForm() if request.method == 'POST': print(request.form) form = CommentForm(request.form) del form.data['submit'] 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)) posts = Post.query.all() 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('comment_response.html', comments=comments, posts=posts, form=form)
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 edit_comment(request, id, com): comment = get_object_or_404(Comment, pk=com) if request.method == "POST": form = CommentForm(request.POST, request.FILES, instance=comment) if form.is_valid(): comment.content = form.save() return redirect(featured_detail, id) else: form = CommentForm(instance=comment) return render(request, 'comments/editcomment.html', {'form': form})
def paste_view(request, pk, paste_set, private_key=None): requested_commit = request.GET.get('commit') user = request.user if not settings.ALLOW_ANONYMOUS_ACCESS and not user.is_authenticated(): return redirect('login') # Increment the views if not paste_set.views: paste_set.views = 0 paste_set.views += 1 paste_set.save() 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 not commit.views: commit.views = 0 commit.views += 1 commit.save() if request.method == 'POST': 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']) editable = False if paste_set.anyone_can_edit or paste_set.owner == request.user: if latest_commit == commit: editable = True # Always clear the comment form comment_form = CommentForm() return render_to_response( 'paste-view.html', { 'paste_set': paste_set, 'pastes': commit.paste_set.all(), 'commit_current': commit, 'favorited': favorited, 'editable': editable, 'comment_form': comment_form, }, RequestContext(request))
def add_comment_into_list(request, storyID): story = mdl_story.get_story(storyID) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): mdl_comment.create_comment(story, request.POST) else: form = CommentForm() comments = mdl_comment.get_comments_for_story(story) context = {'story': story, 'comments': comments, 'newform': form} return render(request, 'CommentList.html', context)
def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return HttpResponseRedirect('/spectre/') else: form = CommentForm() return render(request, 'add_comment_to_post.html', {'form': form})
def thread(request, pk): """List of posts in a thread.""" user = request.user try: profile_obj = user.get_profile() except ObjectDoesNotExist: raise Http404 posts = Post.objects.filter(thread=pk) # # 20 posts in a page, can be furthered improved using ajax load on scroll posts = mk_paginator(request, posts, 20) views = thread_view(request, pk) thread = Thread.objects.get(pk=pk) is_owner = False if thread.creator == request.user: is_owner = True is_admin = False forum = Forum.objects.get(thread__pk=pk) 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 request.method == 'POST': p = request.POST form = CommentForm(p) if form.is_valid(): Post.objects.create(thread=thread, title="re:%s" % thread.title, body=p['body'], creator=request.user, first_post=False) increment_post_counter(request) return HttpResponseRedirect( reverse("forum.views.thread", args=[thread.pk]) + "?page=last") else: form = CommentForm() return render_to_response("forum/thread.html", add_csrf(request, views=views, posts=posts, pk=pk, thread=thread, forum_pk=thread.forum.pk, form=form, profile=profile_obj, is_admin=is_admin, is_owner=is_owner), context_instance=RequestContext(request))
def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/comment_form.html', {'form': form})
def add_comment_to_article(request, pk): article = get_object_or_404(Article, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.article = article comment.save() return redirect('/get/' + str(article.pk), pk=article.pk) else: form = CommentForm() return render(request, 'login_reg/add_comment_to_article.html', {'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 # link btw article and comment c.save() return HttpResponseRedirect('/articles/get/%s' % article_id) else: f = CommentForm() return render(request, 'add_comment.html', {'form': f, 'article': a})
def render_blogentry_page(request, entry_id): if (request.method == "POST"): form = CommentForm(request.POST, request.FILES) if (form.is_valid()): title = request.POST['name'] message = request.POST['message'] comment = Comment(article_id=entry_id, name=title, content=message) comment.save() else: form = CommentForm() entry = Entry.objects.filter(id=entry_id)[0] comments = Comment.objects.filter(article_id=entry_id) context = {'entry': entry, 'comments': comments, 'form': form} return render(request, 'blog_entry.html', context)
def new_comment(request,id): post = get_object_or_404(Post,id=id) user_id=request.user.id print id if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post_comment_id_id = id comment.author_id=int(user_id) comment.check_func() return details(request,post.id) else: form = CommentForm() return render(request, 'geeks/new_comment.html', {'form': form})
def new_item(request): ret = check_auth(request) if ret: return ret if request.method == 'POST': print request.POST if request.GET["new"] == "ticket": form = TicketForm(request.POST) print "valid", form.errors if form.is_valid(): a = Ticket() a.title = form.cleaned_data["title"] a.text = form.cleaned_data["text"] a.priority = form.cleaned_data["priority"] a.author = request.user a.save() send_mail_ticket(a.group, "new_ticket") return show_item(request, a.id) form = {"ticket": TicketForm(), "comment": CommentForm()} return render_to_response('ticket_new.html', {'forms': form, }, context_instance=RequestContext(request))
def add_exercise_comment(category_id, exercise_id): """Handle comment for an exercise.""" # This is a private endpoint, check if user is logged in if "username" not in session: raise Unauthorized() form = CommentForm() username = session['username'] if form.validate_on_submit(): user = User.query.filter_by(username=username).first() content = form.content.data exercise_comment = ExerciseComment(exercise_id=exercise_id, user_id=user.id, content=content) db.session.add(exercise_comment) db.session.commit() return redirect(f"/exercises/{category_id}/{exercise_id}")
def display_exercise(category_id, exercise_id): """Display info on a single exercise.""" # This is a private endpoint, check if user is logged in if "username" not in session: raise Unauthorized() exercise = Exercise.query.get_or_404(exercise_id) comments = ExerciseComment.query.filter_by(exercise_id=exercise_id) comment_count = comments.count() user = User.query.filter_by(username=session['username']).first() user_exercise = UserExercise.query.filter_by( user_id=user.id, exercise_id=exercise_id).first() form = CommentForm() return render_template("exercise/exercise.html", exercise=exercise, comments=comments, form=form, user=user, user_exercise=user_exercise, comment_count=comment_count)
def comment(request, id): print("enter!!!") context = {} print(Post.objects.all()) print("comment!!") post = get_object_or_404(Post, id=id) if (not post): context['error'] = 'The post does not exist.' return render(request, 'grumblr/comments.json', context, content_type='application/json') new_comment = Comment.objects.create(author_user_profile=get_object_or_404( UserProfile, user=request.user), time=datetime.datetime.now(), post=post) comment_form = CommentForm(request.POST, instance=new_comment) if not comment_form.is_valid(): context['error'] = 'The comment is invalid.' return render(request, 'grumblr/comments.json', context, content_type='application/json') new_comment = comment_form.save() context['comment'] = new_comment return render(request, 'grumblr/comment.html', context)
def following_page(request): current_user_profile = get_object_or_404(UserProfile, user=request.user) errors = [] comment_list = [] # query all posts that are posted by users in the current user's following list post_list = Post.objects.filter(user_profile__in=current_user_profile. following.all()).order_by("-date") # create comment forms for each post comment_form = CommentForm() if not post_list: errors.append("There are not any posts in the following list.") for post in post_list: post.count = Comment.objects.filter(post=post).count() # get comments by each post comment_list = Comment.objects.filter(post=post).order_by("time") setattr(post, 'comment_list', comment_list) # get the latest post with max id max_id = 0 if Post.objects.count() > 0: max_id = Post.objects.all().order_by("-id")[0].id return render( request, 'grumblr/following_stream.html', { "object_list": post_list, "current_user": request.user, "errors": errors, 'comment_list': comment_list, "max_id": max_id, 'comment_form': comment_form })
def globalstream(request): errors = [] # get all the posts in the global stream by reverse-chronological order post_list = Post.objects.all().order_by("-date") # create a bound form for updating a post post_form = PostForm() # create comment forms for each post comment_form = CommentForm() if not post_list: errors.append("There are not any posts in Grumblr.") for post in post_list: post.count = Comment.objects.filter(post=post).count() # get comments by each post comment_list = Comment.objects.filter(post=post).order_by("time") setattr(post, 'comment_list', comment_list) # get the latest post with max id max_id = 0 if Post.objects.all(): max_id = Post.objects.all().order_by("-id")[0].id return render( request, 'grumblr/globalstream.html', { "object_list": post_list, "current_user": request.user, "errors": errors, "post_form": post_form, "max_id": max_id, "comment_form": comment_form })
def comment_view(request): user = check_validation(request) if user and request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): post_id = form.cleaned_data.get('post').id comment_text = form.cleaned_data.get('comment_text') comment = CommentModel.objects.create(user=user, post_id=post_id, comment_text=comment_text) comment.save() sg = sendgrid.SendGridAPIClient(apikey=(sendgrid_key)) from_email = Email("*****@*****.**") to_email = Email(comment.post.user.email) subject = "Welcome to My App" content = Content("has been commented", "commented/n") mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) return redirect('/feed/') else: return redirect('/feed/') else: return redirect('/login')
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 post(id): post = Post.query.get_or_404(id) form = CommentForm() if form.validate_on_submit(): comment = Comment(body=form.body.data, post=post, author=current_user._get_current_object()) db.session.add(comment) flash('Your comment has been published') return redirect(url_for('.post', id=post.id, page=-1)) page = request.args.get('page', 1, type=int) if page == -1: page = (post.comments.count() -1)//\ current_app.config['COMMENTS_PER_PAGE'] + 1 pagination = post.comments.filter_by(parrent_id=None).order_by( Comment.timestamp.asc()).paginate( page, per_page=current_app.config['COMMENTS_PER_PAGE'], error_out=False) comments = pagination.items return render_template('post.html', posts=[post], post_form=form, comments=comments, pagination=pagination, Comment=Comment)
def comments(request, subdomain, article_id): try: wiki = models.Wiki.objects.get(subdomain=subdomain) story = models.Story.objects.get(id=article_id, wiki=wiki) except ObjectDoesNotExist: return four_oh_four(request) if request.method == "POST" and request.user.is_authenticated(): text = request.POST.get('text') if text is not None and text.strip() is not "": parent_id = request.POST.get('parent_id') if parent_id is not None: try: parent = models.Comment(id=parent_id, story=story) new_comment = models.Comment(story=story, parent=parent, text=text, user=request.user) new_comment.save() except ObjectDoesNotExist: pass else: new_comment = models.Comment(story=story, text=text, user=request.user) new_comment.save() current_comments = [ c for c in models.Comment.objects.filter(id=article_id) ] return render_to_response('comments.html', dict(story=story, comments=current_comments, wiki=wiki, comment_form=CommentForm()), context_instance=RequestContext(request))
def add_comment(request): if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): client = get_object_or_404(Client, pk=form.cleaned_data['client_id']) selection = get_object_or_404(Selection, pk=form.cleaned_data['selection_id']) if form.cleaned_data['text'] != '': author = request.user comment_text = form.cleaned_data['text'] comment = Comment(author=author, text=comment_text, selection=selection) comment.save() if form.cleaned_data['rating'] != '': Rating.objects.update_or_create( rater=request.user, talent=selection.talent, defaults={'rating': form.cleaned_data['rating']}) selection.talent.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER'), { 'selection': selection, 'client': client }) else: return Http404("That page does not exist")