def topic(request, topic_id): try: topic_id_int = int(topic_id) except ValueError: raise Http404() if request.method == 'POST': topic = get_object_or_404(Topic, pk=topic_id_int) user = request.user form = CommentForm(request.POST) if form.is_valid(): new_text_comment = form.cleaned_data['text'] else: new_text_comment = 'not valid comment!' new_comment = Comment(text=new_text_comment, pub_date=timezone.now(), topic=topic, creator=user) new_comment.save() topic = get_object_or_404(Topic, pk=topic_id_int) form = CommentForm() return render_to_response('forum/topic.html', {'topic': topic, 'form': form}, context_instance=RequestContext(request))
def post(self, request, context={}, *args, **kwargs): if not 'id' in self.kwargs: return HttpResponseRedirect(reverse('_finding')) id = self.kwargs['id'] try: thread = Thread.objects.get(id=id) except Exception as e: return _Http404(request) comment_form = CommentForm(request.POST) if comment_form.is_valid(): m = comment_form.save(commit=False) m.create_user = request.user m.thread_id = id m.save() try: t = Thread.objects.get(id=id) t.reply = t.reply + 1 t.save() except Exception as e: pass # get comment list from databases comment_list = Comment.objects.filter(thread_id=id) # get comment list from databases return super().post( request, { 'thread': thread, 'tid': id, 'comment_form': comment_form, "comment_list": comment_list }, *args, **kwargs)
def new_comment_view(request, post_id): doge_user = DogeUser.objects.get(user=request.user) form = CommentForm(data=request.POST) post = get_object_or_404(Post, pk=post_id) if form.is_valid(): form.create_comment(doge_user, post) return thread_redirect(post.thread.id) return HttpResponseRedirect(reverse('index'))
def get_comment(request, pk): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): creator = form.cleaned_data['name'] text = form.cleaned_data['comment'] thread = Thread.objects.get(pk=pk) Comment(text=text, thread=thread, creator=creator).save() messages.success(request, 'Thanks for commenting, dude') return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
def ajax_view(request): form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.save() return JsonResponse({ "comment": '{} - {}'.format(datetime.now(), comment.content), 'pk': comment.pk })
def comment(post_id): form = CommentForm() #Check if comment is made if form.validate_on_submit(): comment = Activity(comment=form.comment.data, id=current_user.id, post_id=post_id) db.session.add(comment) db.session.commit() author_email = db.session.execute("SELECT email FROM User a JOIN Post b ON b.id = a.id WHERE b.post_id = " + str(post_id)).fetchall() subject = 'Someone has commented in your post.' message = current_user.email + ' New User Comment "' + form.comment.data + '" on your post at http://localhost:5000/post/' + str(post_id) + '.' send_email(subject, '*****@*****.**', [author_email[0].email], message, message) flash('Comment successfully added!', 'success') # comments_count = comments_count + 1; return redirect(url_for('post', post_id=post_id))
def commented(): form = CommentForm() # sort date if request.args.get('date') and request.args.get('date') == 'desc': column_name = 'a.date_created' order = 'DESC' elif request.args.get('date') and request.args.get('date') == 'asc': column_name = 'a.date_created' order = 'ASC' # sort upvote elif request.args.get('upvote') and request.args.get('upvote') == 'desc': column_name = 'upvote_count' order = 'DESC' elif request.args.get('upvote') and request.args.get('upvote') == 'asc': column_name = 'upvote_count' order = 'ASC' # sort comment elif request.args.get('comment') and request.args.get('comment') == 'desc': column_name = 'comments_count' order = 'DESC' elif request.args.get('comment') and request.args.get('comment') == 'asc': column_name = 'comments_count' order = 'ASC' else: column_name = 'a.post_id' order = 'DESC' # main query posts = db.session.execute("SELECT a.post_id, a.title, a.body, a.image, a.date_created, c.email, c.profile_picture, (SELECT COUNT(1) FROM Activity WHERE post_id=a.post_id AND comment <> 'None') AS comments_count, (SELECT COUNT(1) FROM Activity WHERE post_id=a.post_id AND upvote = 1) AS upvote_count, (SELECT COUNT(1) FROM Activity WHERE post_id=a.post_id AND downvote = 1) AS downvote_count FROM Post a JOIN Activity b ON b.post_id = a.post_id JOIN User c ON c.id = a.id WHERE b.id = " + str(current_user.id) + " AND b.comment <> 'None' GROUP BY a.post_id ORDER BY " + column_name + " " + order).fetchall() return render_template('home.html', title='Commented Posts', posts=posts, form=form)
def home(): form = CommentForm() # DATE SORT if request.args.get('date') and request.args.get('date') == 'desc': column_name = 'a.date_created' order = 'DESC' elif request.args.get('date') and request.args.get('date') == 'asc': column_name = 'a.date_created' order = 'ASC' # UPVOTE SORT elif request.args.get('upvote') and request.args.get('upvote') == 'desc': column_name = 'upvote_count' order = 'DESC' elif request.args.get('upvote') and request.args.get('upvote') == 'asc': column_name = 'upvote_count' order = 'ASC' # COMMENT SORT elif request.args.get('comment') and request.args.get('comment') == 'desc': column_name = 'comments_count' order = 'DESC' elif request.args.get('comment') and request.args.get('comment') == 'asc': column_name = 'comments_count' order = 'ASC' else: column_name = 'a.post_id' order = 'DESC' posts = db.session.execute("SELECT a.post_id, a.title, a.body, a.image, a.date_created, c.email, c.profile_picture, (SELECT COUNT(1) FROM Activity WHERE post_id=a.post_id AND comment <> 'None') AS comments_count, (SELECT COUNT(1) FROM Activity WHERE post_id=a.post_id AND upvote = 1) AS upvote_count, (SELECT COUNT(1) FROM Activity WHERE post_id=a.post_id AND downvote = 1) AS downvote_count FROM Post a LEFT JOIN Activity b ON b.post_id = a.post_id LEFT JOIN User c ON c.id = a.id GROUP BY a.post_id ORDER BY " + column_name + " " + order).fetchall() return render_template('home.html', title="Home", posts=posts, form=form)
def forum_all(request): threads = Thread.objects.all() cform = CommentForm() return render(request, 'forum/forum_all.html', { 'threads': threads, 'cform': cform })
def get_context_data(self, **kwargs): context = super(TopicView, self).get_context_data(**kwargs) board = Board.objects.get(slug=self.kwargs.get('slug')) context['board'] = board context['comment_form'] = CommentForm(source=self.get_object(), commenter=self.request.user) context['comments'] = self.object.comment_set.all() return context
def post_details(request, pk): le_post = get_object_or_404(Post, id = pk) if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_obj = Comment.objects.get(id=parent_id) if parent_obj: replay_comment = comment_form.save(commit=False) replay_comment.parent = parent_obj new_comment = comment_form.save(commit=False) new_comment.name = request.user new_comment.post = le_post new_comment.save() return redirect('post_details', pk = le_post.id) le_post = get_object_or_404(Post, id = pk) comments = Comment.objects.all() post_comments = [] for comment in comments: if comment.post == le_post: post_comments.append(comment) comment_form = CommentForm() return render(request, 'forum/post_details.html',{'post': le_post, 'comments': post_comments,'comment_form': comment_form})
def thread(request, thread_id): thread = get_object_or_404(Thread, pk=thread_id) if request.POST and request.user.is_authenticated(): form = CommentForm(request.POST) if form.is_valid(): form.save(thread, request.user) thread.last_comment_date = datetime.now() thread.save() return HttpResponseRedirect(reverse('forum_thread', args=[thread_id])) else: form = CommentForm() return render_to_response(request, 'forum/thread.html', {'thread': thread, 'user': request.user.is_authenticated() and request.user or None, 'comments': Comment.objects.filter(thread=thread).order_by('date_created'), 'form': form, })
def comment(request): college_list = College.objects.all() path = request.path if request.method == 'POST': form = CommentForm(data=request.POST, auto_id="%s") if form.is_valid(): article_id = request.POST.get('article') article = Article.objects.get(pk=article_id) comment = form.cleaned_data["comment"] if len(comment) > 0: article_comment = ArticleComment(user=request.user, article=article, comment=comment) article_comment.save() return render(request, 'page.html', { 'article': article, 'college_list': college_list }) # @login_required # # @ajax_required # def comment(request): # path = request.path # if request.method == 'POST': # form = CommentForm(data=request.POST, auto_id="%s") # if form.is_valid(): # article_id = request.POST.get('article') # article = Article.objects.get(pk=article_id) # comment = form.cleaned_data["comment"] # if len(comment) > 0: # article_comment = ArticleComment(user=request.user,article=article,comment=comment) # article_comment.save() # html = '' # for comment in article.get_comments(): # html = '{0}{1}'.format(html, render_to_string('partial_article_comment.html', # {'comment':comment})) # # return render(request,'page.html',{'article':article}) # return HttpRepsonse(html)
def PostComment(request): commentform = CommentForm(request.POST) message = {'message': 'something wrong!'} print(request.POST) if(commentform.is_valid()): comment=commentform.save(commit=False) if request.user.is_authenticated(): comment.author = request.user comment.end=request.POST['end'] comment.start=request.POST['start'] comment.title=request.POST['title'] comment.object_id=request.POST['object_id'] comment.content_type=ContentType.objects.get_for_model(Timelike) if (request.POST['isBasic']=='on'): comment.isBasic=True else: comment.isBasic=False comment.save() newComment = Comment.objects.latest('pubDate') message = newComment.singlejson() print(message) return HttpResponse(json.dumps(message))
def create_comment(request, module_name_slug, question_page_name_slug, question_post=None): context_dict = {} module = Module.objects.get(slug=module_name_slug) question_page = QuestionPage.objects.get(slug=question_page_name_slug) question_posts = QuestionPost.objects.filter(page=question_page) comments = Comment.objects.filter(post__in=question_posts) if request.method == 'POST': post_form = QuestionPostForm comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Save comment instance comment = comment_form.save(commit=False) q_post = question_post # request.POST.get('question_post') comment.post = get_object_or_404(QuestionPost, pid=q_post) comment.user_profile = UserProfile.objects.get(user=request.user) comment.save() else: # Invalid form(s): Print errors to console/log print(comment_form.errors) comment_form = CommentForm else: comment_form = CommentForm post_form = QuestionPostForm context_dict['question_posts'] = question_posts context_dict['question_page'] = question_page context_dict['comments'] = comments context_dict['module'] = module context_dict['post_form'] = post_form context_dict['comment_form'] = comment_form return HttpResponseRedirect('/forum/questions/%s/%s/' % (module.slug, question_page.slug))
def add_reply_to_comment(request, pk, id): """Allow adding a reply to a post comment""" comment = get_object_or_404(Comment, id=id) post = get_object_or_404(Post, pk=pk) user = request.user if request.method == "POST": form = CommentForm(request.POST or None) if form.is_valid(): text = request.POST.get('text') reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create(post=post, reply=comment_qs, author=user, text=text, approved_comment=True) comment.save() messages.success(request, "Your reply has been successfully added") return HttpResponseRedirect(post.get_absolute_url()) else: form = CommentForm() return render(request, 'forum/reply_form.html', {'form': form, 'comment': comment})
def forum_content(request, id): try: post = Post.objects.get(id=int(id)) except: HttpResponseRedirect('/forum_index') delete_id = None delete_id = request.POST.get('delete_id', '') try: delcomment = Comment.objects.get(id=int(delete_id)) delcomment.post.save() delcomment.delete() except Exception: pass if request.user.is_authenticated(): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): cd = form.cleaned_data comment = Comment(content=cd['comment'], post=Post.objects.get(id=int(id)), replier=request.user) comment.save() comment.post.save() else: form = CommentForm() print(4) commentlist = post.p_comment.all() return render(request, 'forum_content_after_login.html', { 'post': post, 'commentlist': commentlist }) else: commentlist = post.p_comment.all() return render(request, 'forum_content.html', { 'post': post, 'commentlist': commentlist })
def get(self, request, context={}, *args, **kwargs): if not 'id' in self.kwargs: return HttpResponseRedirect(reverse('_finding')) id = self.kwargs['id'] try: t = Thread.objects.get(id=id) t.view = t.view + 1 t.save() except Exception as e: pass try: thread = Thread.objects.get(id=id) except Exception as e: return _Http404(request) comment_form = CommentForm() # get comment list from databases comment_list = Comment.objects.filter(thread_id=id) # get like from databased liked = False if request.user.is_authenticated(): tl = ThreadLike.objects.filter(thread=thread, user=request.user) if tl: liked = True # get_collected from database collected = False if request.user.is_authenticated(): cl = Collection.objects.filter(thread=thread, create_user=request.user) if cl: collected = True tag_set = thread.tag_set.all() return super().get( request, { 'thread': thread, 'tag_set': tag_set, 'tid': id, 'comment_form': comment_form, "comment_list": comment_list, "liked": liked, "collected": collected }, *args, **kwargs)
def post(self, request, pk, slug): post = get_object_or_404(Post, pk=pk, slug=slug) if request.method == "POST": form = self.form_class(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.post = post comment.save() return redirect('forum:post_detail', pk=post.pk, slug=post.slug) else: form = CommentForm() return render(request, self.template_name, {'form': form})
def Addcomment1(request,article_id): if request.method == 'POST' and ("pause" not in request.session): form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comments_article = Article.objects.get(id=article_id) qwe = auth.get_user(request).username comment.comments_from = User.objects.get_by_natural_key(qwe) form.save() #request.session.set_expiry(60) #request.session['pause'] = True return HttpResponseRedirect('/forum/forum_article/%s' % article_id)
def post_comment(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, 'forum/post_comment.html', {'form': form})
def post(post_id): post = Post.query.get_or_404(post_id) comments = Activity.query.filter_by(post_id=post_id) comments_count = 0 #comments_count = Activity.query.filter_by(post_id=post_id).count() for comment in comments: if comment.comment: comments_count += 1 comment_form = CommentForm() upvote_count = Activity.query.filter_by(post_id=post_id, upvote=True).count() downvote_count = Activity.query.filter_by(post_id=post_id, downvote=True).group_by(Activity.id).count() return render_template('post.html', title=post.title, post=post, comment_form=comment_form, comments=comments, comments_count=comments_count, upvote_count=upvote_count, downvote_count=downvote_count)
def forum(request): last_five = Thread.objects.all().order_by('-id')[:5] if request.method == 'POST': form = ThreadForm(request.POST) if form.is_valid(): creator = form.cleaned_data['name'] text = form.cleaned_data['subject'] Thread(text=text, creator=creator).save() messages.success(request, 'Thanks for getting involved, dude') return redirect(reverse('forum:forum')) else: form = ThreadForm() cform = CommentForm() return render(request, 'forum/forum.html', { 'last_five': last_five, 'form': form, 'cform': cform })
def post(self, request, pk, slug): post = get_object_or_404(Post, pk=pk, slug=slug) if request.method == "POST": form = self.form_class(request.POST or None) if form.is_valid(): reply_id = int(request.POST.get('comment_pk')) text = request.POST.get('id_message') comment_qs = None if reply_id: comment_qs = Comment.objects.get(pk=reply_id) comment = Comment.objects.create(post=post, user=request.user, text=text, reply=comment_qs) comment.save() return redirect('forum:post_detail', pk=post.pk, slug=post.slug) else: form = CommentForm() return render(request, self.template_name, {'form': form})
def add_comment_to_post(request, pk): """Allow adding a comment to a post""" post = get_object_or_404(Post, pk=pk) user = request.user if request.method == "POST": form = CommentForm(request.POST or None) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = user comment.save() messages.success(request, "Your comment is pending approval...") return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'forum/comment_form.html', {'form': form})
def get_one_article(request, **kwargs): if request.method == 'GET': form = CommentForm() article = Article.objects.get(pk=kwargs['pk']) comments = article.comment_article.all() return render(request, 'forum/detail_article.html', {"article": article, 'comments': comments, 'form': form}) if request.method == 'POST': form = CommentForm(request.POST) article = Article.objects.get(pk=kwargs['pk']) if form.is_valid(): comment = form.save(commit=False) comment.article = article comment.publisher = UserProfile.objects.get(user=request.user) comment.save() return redirect('one_article', pk=kwargs['pk']) return redirect('one_article', pk=kwargs['pk'])
def query_detail(request, pk): ''' function to show a single post detail, also displays any comments associated with a post and allows logged in users to add comments to post ''' query_detail = get_object_or_404(Post, pk=pk) # getting current session user user = request.user # Creating comment form comment_form = CommentForm() # if form is submitted if request.method == 'POST': # checking user is logged in logged_user = request.user.id # dont let non logged in user add comment if not logged_user: messages.warning(request, f'You must be logged in to comment') return redirect('posts') # take submitted form comment_form = CommentForm(request.POST or None) # if submitted form is valid save it to db if comment_form.is_valid(): comment = comment_form.save(commit=False) # link query foregin key comment.query = query_detail # adding query detail to title field comment.title = query_detail.title # adding user to foreign key field comment.comment_by = user comment.save() # message user and reload post detail page messages.success(request, f'Comment added sucessfully') return redirect('post-detail', pk=query_detail.pk) # finding comments related to current post comments = Comment.objects.filter(query_id=pk) # adding to context and returning to post detail page context = { "post": query_detail, "comments": comments, "form": comment_form } return render(request, "forum/post_detail.html", context)
def newcomment(request, cat_id, thd_id, pst_id): if not request.user.is_authenticated(): return redirect(reverse(index)) else: try: post = Post.objects.get(pk=pst_id) except Post.DoesNotExist: url = ''.join(('/agora/', str(cat_id), '/', str(thd_id), '/')) return redirect(url, request) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): new = form.save(commit=False) new.author = request.user new.date = datetime.datetime.now() new.parent = post new.save() url = ''.join(('/agora/', str(cat_id), '/', str(thd_id), '/')) return redirect(url, request) else: form = CommentForm() return render(request, 'newcomment.html', locals())
def topic_comment(request, slug, subtitle): topic = get_object_or_404(Topic, subtitle=subtitle) CommentForm(request.POST, source=topic, commenter=request.user).save() return redirect('topic', slug=topic.board.slug, subtitle=topic.subtitle)
def test_post_form(self): form_data = {'title': 'djangotest', 'content': 'this is a post'} form = CommentForm(data=form_data) self.assertTrue(form.is_valid())
def test_fields_are_explicit_in_form_metaclass(self): """ test correct fields are displayed in the form """ form = CommentForm() self.assertEqual(form.Meta.fields, ['body'])
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comment_form'] = CommentForm(initial={'post': self.object}) context['comments'] = Comment.objects.filter(post=self.object) return context
def test_comment_form_is_not_valid(self): form = CommentForm(data={}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1)
def test_comment_form_valid(self): form = CommentForm(data={'text': 'hej'}) self.assertTrue(form.is_valid())