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 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 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_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 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_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 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 get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['category_list'] = self.object.category.all() context['comment_list'] = Comment.get_comment( post_pk=self.object.id).filter(origin=None) context['all_category'] = Category.objects.all().order_by('ordering') context['days'] = (timezone.localdate() - self.object.modified).days return 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(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 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, 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 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 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 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 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 post_comment(request): # 获取信息 post_id = int(request.POST.get('post_id', 0)) comment = request.POST.get('comment', '') # 生成评论 Comment( content=comment, author=request.user, post=Post.objects.get(pk=post_id) ).save() return redirect(reverse("index:post_show", kwargs={'post_id': post_id, 'comment_page': 1}))
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 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 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 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 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 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)
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 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 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 get_form_kwargs(self): form_kwargs = super(CommentCreateView, self).get_form_kwargs() post = Post.objects.get(pk=self.kwargs['post_pk']) instance = Comment(post=post) form_kwargs['instance'] = instance return form_kwargs
async def receive(self, text_data): text_data_json = json.loads(text_data) print(text_data_json) try: comment = text_data_json['comment'] print(comment) # Save comments to database comment_obj = Comment(commentor=self.me, post=self.post, content=comment, written=dt.datetime.now, modified=dt.datetime.now) await database_sync_to_async(comment_obj.save)() notification_obj = PostNotification( actor=self.me, action='commented on', recipient=self.post.author, post=self.post, notified=dt.datetime.now, ) await database_sync_to_async(notification_obj.save)() # Send comment to room group # These are what will be sent to the post_comment function below await self.channel_layer.group_send( self.room_group_name, { 'type': 'post_comment', 'comment': comment, 'commentor_id': comment_obj.commentor.id, 'commentor_name': comment_obj.commentor.username, 'post_author_id': self.post.author.id, 'notification': notification_obj.actor.username + " commented on your post at " + str(notification_obj.notified), 'target': 'comment', }) except Exception: reaction = text_data_json['reaction'] if reaction == "liked": reaction_obj = Reaction(post=self.post, liker=self.me) await database_sync_to_async(reaction_obj.save)() '''reaction_count = await self.get_reaction_count()''' notification_obj = PostNotification( actor=reaction_obj.liker, action='liked', recipient=self.post.author, post=self.post, notified=dt.datetime.now, ) await database_sync_to_async(notification_obj.save)() # Send comment to room group # These are what will be sent to the post_comment function below await self.channel_layer.group_send( self.room_group_name, { 'type': 'post_reaction', 'liker_id': reaction_obj.liker.id, 'liker_name': reaction_obj.liker.username, 'target': 'reaction', #'reaction_count': reaction_count, 'post_author_id': self.post.author.id, 'notification': notification_obj.actor.username + " liked your post on " + str(notification_obj.notified), 'reaction': reaction, }) else: reaction_obj = await database_sync_to_async( Reaction.objects.get)(post=self.post, liker=self.me) '''reaction_count = await self.get_reaction_count() print(reaction_count)''' notification_obj = await database_sync_to_async( PostNotification.objects.get)( actor=reaction_obj.liker, action='liked', post=reaction_obj.post, ) await database_sync_to_async(reaction_obj.delete)() await database_sync_to_async(notification_obj.delete)() # Send comment to room group # These are what will be sent to the post_comment function below await self.channel_layer.group_send( self.room_group_name, { 'type': 'post_reaction', 'unliker_id': self.me.id, 'unliker_name': self.me.username, 'target': 'reaction', #'reaction_count': reaction_count, 'reaction': reaction, })
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): 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 profile_page(request, username): # Requests if request.method == 'POST': # follow if request.POST.get('name', '') == 'follow': follower = request.POST.get('follower', '') following = request.POST.get('following', '') already_follow_check = Follow.objects.filter( follower=User.objects.filter(username=follower).first(), following=User.objects.filter( username=following).first()).count() if already_follow_check == 0: follow = Follow( follower=User.objects.filter(username=follower).first(), following=User.objects.filter(username=following).first()) follow.save() # unfollow elif request.POST.get('name', '') == 'unfollow': follower = request.POST.get('follower', '') following = request.POST.get('following', '') Follow.objects.filter( follower=User.objects.filter(username=follower).first(), following=User.objects.filter( username=following).first()).delete() # like elif request.POST.get('name', '') == 'like': liker = User.objects.filter( username=request.POST.get('liker', '')).first() post = Post.objects.filter( pk=int(request.POST.get('post', ''))).first() already_like_check = Like.objects.filter(post=post, liker=liker).count() if already_like_check == 0: like = Like(post=post, liker=liker).save() # unlike elif request.POST.get('name', '') == 'unlike': liker = User.objects.filter( username=request.POST.get('liker', '')).first() post = Post.objects.filter( pk=int(request.POST.get('post', ''))).first() Like.objects.filter(post=post, liker=liker).delete() # Add comment elif request.POST.get('name', '') == 'add_comment': comment = request.POST.get('comment', '') commenter = User.objects.filter( username=request.POST.get('commenter', '')).first() post = Post.objects.filter( pk=int(request.POST.get('post', ''))).first() comment = Comment(post=post, commenter=commenter, comment=comment).save() # fetch comment elif request.POST.get('name', '') == 'comment_load': limit = 5 offset = request.POST.get('offset', '') offset = int(offset) post_pk = request.POST.get('post', '') post = Post.objects.filter(pk=post_pk).first() comments = Comment.objects.filter(post=post) if comments.first() != None: comments = list(comments)[-offset:-(limit + offset):-1] comments_json = serializers.serialize('json', comments) u_d = [] u__d = [] c_time_passed = [] for i in comments: temp = Profile.objects.filter(user=i.commenter).first() u_d.append(temp) u__d.append(i.commenter) # Calculating the time passed since the comment has been posted # Split and get a list dt = str(i.date).split('-') # Taking 0th element because it is hour and we don't need mins and seconds t = str(i.time).split(':') # Now we have data like this - [Year, Month, Date, Hour] dt.append(t[0]) dt.append(t[1]) # Now we have data corresponding to the current time - [Year, Month, Date, Hour] r_dt = [ time.strftime('%Y'), time.strftime('%m'), time.strftime('%d'), time.strftime('%H'), time.strftime('%M') ] if r_dt[0] == dt[0]: # year tp = f'{int(r_dt[1]) - int(dt[1])} months ago' if r_dt[1] == dt[1]: # month tp = f'{int(r_dt[2]) - int(dt[2])} days ago' if r_dt[2] == dt[2]: # date tp = f'{int(r_dt[3]) - int(dt[3])} hours ago' if r_dt[3] == dt[3]: # hour if (int(r_dt[4]) - int(dt[4])) == 0: tp = 'Few seconds ago' else: tp = f'{int(r_dt[4]) - int(dt[4])} minutes ago' c_time_passed.append(tp) u_d_json = serializers.serialize('json', u_d) u__d_json = serializers.serialize('json', u__d) return JsonResponse( data={ 'comments': comments_json, 'u_d': u_d_json, 'u__d': u__d_json, 'c_time_passed': c_time_passed, 'total': Comment.objects.filter(post=post).count(), }) else: return JsonResponse( data={ 'comments': None, 'u_d': None, 'u__d': None, 'c_time_passed': None, 'total': None, }) # Rating elif request.POST.get('name', '') == 'rate': user = User.objects.filter( username=request.POST.get('user', '')).first() page = User.objects.filter( username=request.POST.get('page', '')).first() rating = request.POST.get('rating', '') Rate(user=user, page=page, rating=int(rating)).save() # User exists or not elif request.POST.get('name', '') == 'user_exists': user = User.objects.filter( username=request.POST.get('username', '')).first() if user == None: return JsonResponse(data={ 'exists': False, }) return JsonResponse(data={ 'exists': True, }) elif request.POST.get('name', '') == 'tagged_user_profile': username = request.POST.get('username', '') user = User.objects.filter(username=username) profile = Profile.objects.filter(user=user.first()) following = Follow.objects.filter(follower=user.first()).count() follower = Follow.objects.filter(following=user.first()).count() posts = Post.objects.filter(user=user.first()).count() u = serializers.serialize('json', user) p = serializers.serialize('json', profile) return JsonResponse( data={ 'user': u, 'profile': p, 'following': following, 'follower': follower, 'posts': posts, }) visit_user = get_object_or_404(User, username=username) # Variables to be sent visit = Profile.objects.filter(user=visit_user).first() try: auth = Profile.objects.filter(user=request.user).first() except: auth = None # Follow vars if auth != None: following = Follow.objects.filter(following=visit.user, follower=auth.user).count() else: following = None # Posts posts = Post.objects.filter(user=visit.user) num_of_total_likes = 0 p = [] if auth != None: for i in posts: l = Like.objects.filter(post=i, liker=auth.user).count() c = Like.objects.filter(post=i).count() co = Comment.objects.filter(post=i).count() p.append([i, l, c, co]) num_of_total_likes += Like.objects.filter(post=i).count() elif auth == None: for i in posts: c = Like.objects.filter(post=i).count() co = Comment.objects.filter(post=i).count() p.append([i, 0, c, co]) num_of_total_likes += Like.objects.filter(post=i).count() # stats num_of_followers = round_number( Follow.objects.filter(following=visit.user).count()) num_of_following = round_number( Follow.objects.filter(follower=visit.user).count()) # Rating if auth != None: rated = Rate.objects.filter(user=auth.user, page=visit.user).count() else: rated = None num_of_people_rated = 0 page_rating = 0 if Rate.objects.filter(page=visit.user).count() != 0: p_r_d = list(Rate.objects.filter(page=visit.user)) for i in p_r_d: num_of_people_rated += 1 page_rating += i.rating page_rating = int(page_rating / num_of_people_rated) params = { 'visit': visit, 'auth': auth, 'following': following, 'num_of_followers': num_of_followers, 'num_of_following': num_of_following, 'posts': p, 'num_of_total_likes': num_of_total_likes, 'rated': rated, 'num_of_people_rated': round_number(num_of_people_rated), 'page_rating': page_rating } return render(request, 'profile_page/index.html', params)
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())