def add_comment(request, pk): form = CommentForm(request.POST) post = get_object_or_404(Post, id=pk) if form.is_valid(): comment = Comment() comment.path = [] comment.comment_post = post comment.author = auth.get_user(request) comment.content = form.cleaned_data['comment_area'] comment.save() # Django не позволяет увидеть ID комментария по мы не сохраним его, # сформируем path после первого сохранения # и пересохраним комментарий try: comment.path.extend( Comment.objects.get( id=form.cleaned_data['parent_comment']).path) comment.path.append(comment.id) except ObjectDoesNotExist: comment.path.append(comment.id) comment.save() return redirect(comment.get_absolute_url())
def post_detail(request, id_): post = Post.objects.get(id=id_) rel_post = Post.objects.order_by('-date_posted').filter( tag=post.tag, for_cooperative__exact=False).all() if request.method == 'POST': content = str(request.POST.get('content', False)) if content: comment = Comment() comment.author_id = request.user.id comment.author_status = author_status(request.user.id) comment.date_posted = timezone.now() comment.content = content comment.post = post comment.save() return redirect('/post/' + str(id_) + '/') else: return render(request, 'post/post_detail.html', { 'post': post, 'related': rel_post }) return render(request, 'post/post_detail.html', { 'post': post, 'related': rel_post })
def post(self, request): data = json.loads(request.body.decode('utf-8')) try: if data['content_input']: new_cm = Comment() new_cm.content = data['content_input'] new_cm.user_id = request.user.id new_cm.post_id = data['post_id'] new_cm.save() return HttpResponse( 'bình luận thành công, hãy tiếp tục tương tác nhé') except: pass z = Comment.objects.filter( post=data['post_id']).order_by('-created_at') comments = [] for i in z: d = model_to_dict(i.user) del d['password'], d['cover_image'], d['avatar'], d['email'], d[ 'date_joined'] out = { **model_to_dict(i), **d, "created_at": i.created_at.strftime("%H:%M:%S ngày %m/%d/%Y") } comments.append(out) return JsonResponse(comments, safe=False)
def post(self, request, *args, **kwargs): new_comment = Comment(cotent=request.POST.get('cotent'), author=self.request.user, post_connected=self.get_object()) new_comment.save() return self.get(self, request, *args, **kwargs)
def get_context_data(self, *, object_list=None, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['title'] = f'{self.object.name}' context['tags'] = get_all_tags(self.object.pk) if self.request.method == 'GET': context['comments'] = Comment.objects.filter( comment_post=self.kwargs['pk']).order_by('path') if self.request.user.is_authenticated: context['form'] = self.comment_form if self.request.method == 'POST': form = CommentForm(self.request.POST) if form.is_valid(): comment = Comment(path=[], comment_post=self.object.pk, author=self.request.user, content=form.cleaned_data['comment_area']) comment.save() # сформируем path после первого сохранения # и пересохраним комментарий try: comment.path.extend( Comment.objects.get( id=form.cleaned_data['parent_comment']).path) comment.path.append(comment.id) # print('получилось') except ObjectDoesNotExist: comment.path.append(comment.id) # print('не получилось') comment.save() return context
def create(self, validated_data): comment = Comment( content=validated_data['content'], user=validated_data['user'], post=Post.objects.get(id=validated_data['post_pk']) ) comment.save() return comment
def save(self, commit=True): comment = Comment() comment.text = self.cleaned_data['text'] comment.user = self.user comment.blog = self.post if commit: comment.save() return comment
def add_comment_to_post(request, slug): post = get_object_or_404(Post, slug=slug) if request.method == "POST": comment = Comment() comment.text = request.POST.get("commentBox") comment.post = post comment.comment_user = request.user comment.save() return redirect('post:postlist') else: return redirect('post:postlist')
def post_comment(request): if request.method == "POST": c = request.POST.get('comment', '').strip(" ") if len(c) > 0: p = Post.objects.get(pk=int(request.POST['post'])) c = Comment(who=request.user, post=p, content=c) c.save() return render_to_response('post/comment.html', context={ 'comment': c, 'post': c.post, })
def add_comment(request, article_id): form = CommentForm(request.POST) post = get_object_or_404(Post, id=article_id) if form.is_valid(): comment = Comment() comment.path = [] comment.post_id = post comment.author_id = auth.get_user(request) comment.content = form.cleaned_data['comment_area'] comment.save() return redirect(post.get_absolute_url())
def save(self): post = self.initial["post"] user = self.initial["user"] parent_object = self.initial["parent_object"] new_comment = Comment() new_comment.comment = self.cleaned_data["comment"] new_comment.post = post new_comment.user = user new_comment.object_id = parent_object.id new_comment.content_type = ContentType.objects.get_for_model(parent_object) new_comment.is_active = True new_comment.activation_code = 0 new_comment.save()
def save(self): post = self.initial["post"] user = self.initial["user"] parent_object = self.initial["parent_object"] new_comment = Comment() new_comment.comment = self.cleaned_data["comment"] new_comment.post = post new_comment.user = user new_comment.object_id = parent_object.id new_comment.content_type = ContentType.objects.get_for_model( parent_object) new_comment.is_active = True new_comment.activation_code = 0 new_comment.save()
def post(self, request): data = json.loads(request.body.decode('utf-8')) try: if data['content_input']: new_cm = Comment() new_cm.content = data['content_input'] new_cm.user_id = request.user.id new_cm.post_id = data['post_id'] new_cm.save() return HttpResponse( 'bình luận thành công, hãy tiếp tục tương tác nhé') except: pass database = Database(request.user.id) get_comment_post_id = database.get_comment_post_id(data['post_id']) return JsonResponse({'result': get_comment_post_id})
def reply(request, *args, **kwargs): if request.method == 'POST': c = Comment() c.uid = request.session['user111'] c.pid = args[0] id = request.GET.get('parent') print(id) c.parent = Comment.objects.filter(id=int(id)).first() c.comment_text = request.POST.get('commet_text') c.save() articalSet = Post.objects.filter(id=args[0]) if articalSet: artical = articalSet[0] else: artical = Post.objects.all()[0] return render(request, 'post/showpost.html', {'artical': artical})
def add_comment(request, post_id): post = get_object_or_404(Post, id=post_id) if request.method == 'POST': user = request.POST['name'] name = request.POST['name'] email = request.POST['email'] text = request.POST['text'] newComment = Comment(user=user, name=name, email=email, text=text, post=post) newComment.post = post newComment.save() messages.success(request, 'Comment added') return redirect(reverse('post_details', kwargs={"post_id": post_id}))
def save(self): parent_object = self.initial["parent_object"] email = self.cleaned_data["email"] post = self.initial["post"] random_int = random.random()*9999 activation_code = hashlib.sha224("%s:%s"%(email,random_int)).hexdigest()[:50] print activation_code new_comment = Comment() new_comment.comment = self.cleaned_data["comment"] new_comment.email = email new_comment.post = post new_comment.activation_code = activation_code new_comment.object_id = parent_object.id new_comment.content_type = ContentType.objects.get_for_model(parent_object) new_comment.is_active = False new_comment.save() send_comment_activation_mail.delay(activation_code, email)
def post_comment(request, post_id): p = Post.objects.get(id=post_id) current_user = request.user if not current_user.is_authenticated: return HttpResponseRedirect(request.META.get('HTTP_REFERER')) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): c = Comment(post=p, author=current_user, date=datetime.now(), content=form.cleaned_data['comment']) c.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def view_post(request, post_id): post = Post.objects.get(id=post_id) if request.method == 'POST': form = CommentForm(data=request.POST) if form.is_valid(): obj = Comment( author=request.user, post=post, comment=form.cleaned_data.get('comment'), timestamp=timezone.now(), ) obj.save() comments = Comment.objects.filter(post=post) context = {'post': post, 'comments': comments} return render(request, 'post.html', context)
def save(self): parent_object = self.initial["parent_object"] email = self.cleaned_data["email"] post = self.initial["post"] random_int = random.random() * 9999 activation_code = hashlib.sha224("%s:%s" % (email, random_int)).hexdigest()[:50] print activation_code new_comment = Comment() new_comment.comment = self.cleaned_data["comment"] new_comment.email = email new_comment.post = post new_comment.activation_code = activation_code new_comment.object_id = parent_object.id new_comment.content_type = ContentType.objects.get_for_model( parent_object) new_comment.is_active = False new_comment.save() send_comment_activation_mail.delay(activation_code, email)
def post_detail(request, pk): post = Post.objects.get(pk=pk) form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment(author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=post) comment.save() comments = Comment.objects.filter(post=post) context = { "post": post, "comments": comments, "form": form, } return render(request, 'post/post_detail.html', context)
def comment(request): user = get_user(request) article_id = request.POST.get('article_id') comment = Comment() comment.article_id = article_id comment.author = user.username comment.content = request.POST.get('content') comment.save() article = Article.objects.filter(id=article_id).first() article.comment_count += 1 article.save() message = '评论成功' add_message(request, messages.INFO, message) current_path = request.POST.get('current_path') return HttpResponseRedirect(current_path)
def add_Comment(request, article_id): form = CommentForm(request.POST) article = get_object_or_404(Article, id=article_id) if form.is_valid(): comment = Comment() comment.path = [] comment.article_id = article comment.author_id = auth.get_user(request) comment.content = form.cleaned_data['comment_area'] comment.save() try: comment.path.extend( Comment.objects.get( id=form.cleaned_data['parent_comment']).path) comment.path.append(comment.id) except ObjectDoesNotExist: comment.path.append(comment.id) comment.save() return redirect(article.get_absolute_url())
def addcomment(request, id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): current_user = request.user data = Comment() data.user_id = current_user.id data.post_id = id data.rate = form.cleaned_data['rate'] data.subject = form.cleaned_data['subject'] data.comment = form.cleaned_data['comment'] data.ip = request.META.get('REMOTE_ADDR') data.save() messages.success(request, "Your comment succesfully send. Thank you") return HttpResponseRedirect(url) messages.warning(request, "Vups, Someting went wrong. Chechk again") return HttpResponseRedirect(url)
def post_answer_comment(request, id): if not request.user.is_authenticated: return redirect('login') answer = get_object_or_404(Answer, pk=id) if request.method == 'POST': content = request.POST.get('comment') if content == '': messages.error(request, '내용을 입력 해 주세요.') return redirect('get_question', id=id) comment = Comment(writer=request.user, content=content) comment.save() answer.comments.add(comment) messages.success(request, '성공적으로 댓글을 작성 하였습니다.') return redirect('get_question', id=Question.objects.get(answers=answer).id) else: messages.error(request, '잘못 된 접근 입니다.') return redirect('get_question', id=Question.objects.get(answers=answer).id)
def post(request, post_id): if request.method == "GET": p = get_object_or_404(Post, pk=post_id) return render_to_response('post/templates/post.html', {'post': p, 'user': request.user}, context_instance=RequestContext(request)) else: print request.POST comment = request.POST.get("comment") if comment: c = Comment() c.post_id = post_id c.comment = comment c.username = request.user.username c.rating = 0 c.save() p = get_object_or_404(Post, pk=post_id) return render_to_response('post/templates/post.html', {'post': p, 'user': request.user}, context_instance=RequestContext(request)) else: return HttpResponse("<strong>you must provide valid comment</strong>")
def comment(request,link): reason="遇到了意料之外的错误" try: post=Post.objects.get(link=link) nickname=request.POST.get('nickname',None) email=request.POST.get('email',None) content=request.POST.get('content',None) if not nickname or not email or not content: reason='缺少必填项' raise Exception() if not validateEmail(email): reason='邮箱格式错误' raise Exception() if len(content)>500: reason='内容长度不能超过500' raise Exception() comment=Comment(nickname=nickname,email=email,content=content,post=post,release_time=datetime.datetime.now(),visible=True) comment.save() except: raise Http404(f'评论保存失败!{reason}。') return redirect(f'/post/{link}#comment-form')
def post_detail_view(request, slug): post = get_object_or_404(Post, slug=slug) post_tags_ids = Tag.objects.all().values_list('id', flat=True) related_posts = Post.objects.filter(status='same_tags').filter( tags__in=post_tags_ids).exclude(slug=post.slug) related_posts = related_posts.annotate(same_tags=Count('tags')).order_by( '-same_tags', '-created')[:4] comments = post.comments.filter(active=True).order_by('-created') category = Category.objects.all() feature = Post.objects.filter(is_featured=True).order_by('-created') if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): body = form.cleaned_data.get('body') new_comment = Comment( body=body, user=request.user, ) new_comment.post = post new_comment.save() return redirect('post-detail', slug=post.slug) else: form = CommentForm() context = { 'post': post, 'related_posts': related_posts, 'feature': feature, 'category': category, 'form': form, 'comments': comments, } return render(request, 'post/detail_page.html', context)