def subcomment_create(request, pk, com_pk): try: article = Article.objects.get(id=pk) try: parent_comment = Comment.objects.get(id=com_pk) if request.method == 'POST': post_nick = request.POST.get('nick') post_body = request.POST.get('body') if not post_nick: return request.META['HTTP_REFERER'] if not post_body: return request.META['HTTP_REFERER'] comment = Comment(nick=post_nick, body=post_body, article=article, comment=parent_comment) comment.save() return render_to_response('articles/comment_detail.html', {'pk': pk, 'nick': post_nick, 'body': post_body, 'article': article, 'parent_comment': parent_comment, 'item': comment}) else: return HttpResponse( json.dumps({"nothing to see": "this isn't happening"}), content_type="application/json" ) except Comment.DoesNotExist: return request.META['HTTP_REFERER'] except Article.DoesNotExist: return request.META['HTTP_REFERER']
def setUp(self): self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.user_2 = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.article = Article.objects.create(title='Test', content="test content", user=self.user) self.comment = Comment(body='test', article=self.article, user=self.user) self.reply = Comment(body='test reply', article=self.article, parent=self.comment, user=self.user) self.article_like = ArticleLike(user=self.user_2, article=self.article) self.special_article_like = ArticleLike(special_like=True, user=self.user_2, article=self.article) self.follow = UserFollowing(user_follows=self.user, user_followed=self.user_2)
def showArticle(request): isSupported = [] if request.method == "POST": commentForm = CommentForm(request.POST) if commentForm.is_valid(): commentInfo = commentForm.cleaned_data user = User.objects.filter(id = commentInfo["publisher"])[0] essay = Essay.objects.filter(id = commentInfo["essayId"])[0] comment = Comment( essay = essay, publisher = user, tend = commentInfo["tend"], content = commentInfo["content"], publish_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), support_num = 0, ) comment.save() return HttpResponseRedirect('/article/?id=' + str(commentInfo["essayId"])) else: essay = Essay.objects.filter(id = request.GET.get('id'))[0] comments = Comment.objects.filter(essay = request.GET.get('id')) for comment in comments: if len(supportCommentRelation.objects.filter(userId = request.GET.get('uid', 0), commentId = comment.id)) != 0: comment.isSupported = True else: comment.isSupported = False commentForm = CommentForm() return render_to_response('article.html', locals(), context_instance = RequestContext(request))
def post(self, request, pk): f = get_object_or_404(Article, id=pk) comment = Comment(text=request.POST['comment'], owner=request.user, article=f) comment.save() return redirect(reverse('articles:article_detail', args=[pk]))
def article_view(request, article_id): # get single story by id article = get_object_or_404(Article, pk=article_id, allowed_to_pub=True, publication_date__lte=datetime.now()) comments = Comment.objects.filter(allowed_to_pub=True, article__pk=article_id).order_by("added_date") # if comment posted if request.method == "POST" and request.user.is_authenticated(): text = request.POST.get("text", None) # if user add empty comment if not text: content = {"article": article, "msg": "Нельзя оставлять пустые комментарии!", "comments": comments} return render(request, "articles/article.html", content) # get current User object u = User.objects.get(pk=request.user.id) # get current UserProfile object profile = UserProfile.objects.get(user=u) # create Comment object c = Comment(text=text, author=profile, article=article) # save comment c.save() return HttpResponseRedirect(reverse("articles:article", kwargs={"article_id": article.id})) # increase views counter article.views += 1 article.save() # prepare page content content = {"article": article, "comments": comments} return render(request, "articles/article.html", content)
def post_comment(request): if request.method == "POST": try: article_id = request.POST['articleId'] comment_text = request.POST['comment'] article = Article.objects.get(pk=article_id) user_id = request.user.id user = CustomUser.objects.get(pk=user_id) comment = Comment(article=article, user=user, text=comment_text) comment.save() serializer = CommentSerializer(comment) return JsonResponse(serializer.data) except Article.DoesNotExist: return JsonResponse(status=404, data={ 'status': 'false', 'message': "Resource not found" }) else: return JsonResponse(status=405, data={ 'status': 'false', 'message': "Method not allowed" })
def new_comment(request, article_id): article = get_object_or_404(Article, pk=article_id) content = request.POST['comment'] author = request.POST['author'] nc = Comment(article=article, contents=content, pub_date=timezone.now(), author=author) nc.save() return HttpResponseRedirect(reverse('articles:article', args=(article_id)))
def mutate_and_get_payload( cls, root, info: AppResolverInfo, article_slug: str, body: str ) -> "CreateCommentMutation": article = Article.objects.get(slug=article_slug) comment = Comment(body=body, author=info.context.user, article=article) comment.save() article.comments.add(comment) return CreateCommentMutation(comment=comment, success=True)
def post(self, request, *args, **kwargs): user_profile = get_object_or_404(UserProfile, user=request.user) article = get_object_or_404(Article, id=kwargs['pk']) comment_content = request.POST['content'] if comment_content: comment = Comment(user_profile=user_profile, article=article, content=comment_content) comment.save() return HttpResponseRedirect(reverse_lazy( 'articles:detail', kwargs=kwargs))
def comment(request): comment = Comment( entry=Entry.objects.get(pk=request.POST['entry_id']), author=User.objects.get(pk=request.POST['author']), comment=request.POST['comment'], ) # if this is a reply to a comment, not to a post if request.POST['parent_id'] != '': comment.parent = Comment.objects.get(pk=request.POST['parent_id']) comment.save() return HttpResponseRedirect(reverse('articles:article', args=(comment.entry.id,)))
def save_comment_view(request): if request.method == 'POST': data = request.POST if data: text = data['text'] user = USER.objects.filter(id=int(data['user'])) post = Article.objects.get(id=int(data['post'])) comment = Comment(text=text, post=post) comment.save() comment.user.set(user) return redirect(f"/articles/detail_post/{request.POST['post']}")
def add_comment(request): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment( body=form.cleaned_data['body'], pub_date=timezone.now(), author=request.user, article=Article.objects.get( id=form.cleaned_data['article_id']), ) comment.save() return render(request, 'ajax_comment.html', {'comment': comment})
class CommentModelTest(TestCase): def setUp(self) -> None: user = User.objects.create( first_name='John', last_name='Doe', email='*****@*****.**' ) self.article = Article( title='some title', text='some text', author=user ) self.comment = Comment( article=self.article, name='some name', email='*****@*****.**', text='some text' ) def test_validate_to_dict_method(self): expected_resp = { 'name': self.comment.name, 'email': self.comment.email, 'text': self.comment.text, 'article': { 'title': self.article.title, 'author_email': self.article.author_email } } self.assertEqual(self.comment.to_dict(), expected_resp)
def setUp(self) -> None: user = User.objects.create( first_name='John', last_name='Doe', email='*****@*****.**' ) self.article = Article( title='some title', text='some text', author=user ) self.comment = Comment( article=self.article, name='some name', email='*****@*****.**', text='some text' )
def article_view(request, article_id): # check if new comment is added if request.method == 'POST': author = request.POST['comment_author'] text = request.POST['comment_text'] # if user didn't specify his name if author == '': author = 'Аноним' article = Article.objects.get(pk=article_id) c = Comment(article=article, comment_author=author, comment_text=text) c.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: article = get_object_or_404(Article, allowed_to_pub=True, pk=article_id) comments_list = Comment.objects.all().filter(allowed_to_view=True, article=article).order_by('creation_date') return render(request, 'articles/article.html', {'article': article, 'comments_list': comments_list})
def showArticle(request): isSupported = [] if request.method == "POST": commentForm = CommentForm(request.POST) if commentForm.is_valid(): commentInfo = commentForm.cleaned_data user = User.objects.filter(id=commentInfo["publisher"])[0] essay = Essay.objects.filter(id=commentInfo["essayId"])[0] comment = Comment( essay=essay, publisher=user, tend=commentInfo["tend"], content=commentInfo["content"], publish_time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), support_num=0, ) comment.save() return HttpResponseRedirect('/article/?id=' + str(commentInfo["essayId"])) else: essay = Essay.objects.filter(id=request.GET.get('id'))[0] comments = Comment.objects.filter(essay=request.GET.get('id')) for comment in comments: if len( supportCommentRelation.objects.filter( userId=request.GET.get('uid', 0), commentId=comment.id)) != 0: comment.isSupported = True else: comment.isSupported = False commentForm = CommentForm() return render_to_response('article.html', locals(), context_instance=RequestContext(request))
def comment(request): if not request.method == 'POST': raise Http404 else: pass try: article_id = request.POST['article_id'] content = request.POST['content'] except: raise Http404 article = get_object_or_404(Article, id=article_id) comment = article.comment_set.filter(user=request.user) if comment: comment = comment[0] comment.content = content else: comment = Comment(user=request.user, content=request.POST['content'], article=article) comment.save() response = json.dumps({'state': comment.id}) return HttpResponse(response)
def setUp(self): uid = uuid.uuid4().hex self.author = User.objects.create(email='{0}@test.com'.format(uid), first_name='test', last_name='user') self.comment = Comment(message='Default test embedded comment', author=self.author) self.post = Post(title='Test Article {0}'.format(uid), content='I am test content', author=self.author, published=True, tags=['post', 'user', 'test'], comments=[self.comment])
def detail(request, slug=None, pk=None): if slug: a = get_object_or_404(Article, slug__exact=slug) elif pk: a = get_object_or_404(Article, pk=pk) else: raise Http404 liked = False if request.user.is_authenticated(): liked = (a.like_set.all() and a.like_set.filter(user=request.user)) if request.method == 'POST': if not request.user.is_authenticated(): return HttpResponseRedirect(reverse(login)) form = CommentForm(request.POST) if form.is_valid(): c = Comment(article=a, user=request.user, text=form.cleaned_data['comment_text']) c.save() return HttpResponseRedirect(a.get_absolute_url()) else: form = CommentForm() return render_to_response('articles/detail.html', {'article': a, 'comment_form': form, 'liked': liked }, context_instance = RequestContext(request))
def setUp(self): CustomUser(username="******").save() Categories(name_category="TestCategory").save() Article( title="TestTitle", content_article="Test Content", id_category=Categories.objects.all()[0], id_user=CustomUser.objects.all()[0], ).save() Comment( id_article=Article.objects.all()[0], id_user=CustomUser.objects.all()[0], content_comment="test comment", ).save() self.all_data_article = AllDataArticle() self.all_data_comment = AllDataComment() self.obj_article = Article.objects.all() self.obj_comment = Comment.objects.all()
def lire(request, id): try: article = Article.objects.get(id=id) except Article.DoesNotExist: raise Http404 try: likes = Like.objects.all().filter(article=article) number_of_likes=len(likes) except: number_of_likes=0 try: like_from_user = Like.objects.all().filter(article=article).filter(auteur=request.user) if len(like_from_user)>0: has_liked=True else: has_liked=False except: has_liked=False form = CommentForm(request.POST or None) # Nous vérifions que les données envoyées sont valides # Cette méthode renvoie False s'il n'y a pas de données # dans le formulaire ou qu'il contient des erreurs. if form.is_valid(): # Ici nous pouvons traiter les données du formulaire new_comment=Comment() new_comment.auteur=request.user new_comment.contenu = form.cleaned_data.get('contenu') new_comment.article = article new_comment.save() try: user_data=UserData.objects.all().filter(user=request.user)[0] user_data.number_articles_he_commented=user_data.number_articles_he_commented+1 user_data.save() except: UserData(request.user).save() try: user_data=UserData.objects.all().filter(user=article.auteur)[0] user_data.number_comments=user_data.number_comments+1 user_data.save() except: UserData(article.auteur).save() # Nous pourrions ici envoyer l'e-mail grâce aux données # que nous venons de récupérer envoi = True try: comments=Comment.objects.all().filter(article=article) except: comments=[] try: signature_object=Signature.objects.get(user=article.auteur) signature = signature_object.signature bio=signature_object.bio has_bio=True if len(bio)==0: has_bio=False if len(signature)<=5: signature = article.auteur.first_name+" "+article.auteur.last_name except: signature = article.auteur.first_name+" "+article.auteur.last_name has_bio=False bio='' if len(signature)<=5: signature = article.auteur.username return render(request, 'blog/lire.html', {'article': article, 'form':form, 'comments': comments, 'has_liked':has_liked, 'number_of_likes':number_of_likes,'signature':signature, 'has_bio':has_bio, 'bio':bio})
def addComment(request, pk): comment = Comment(content=request.POST['content'], article_id=pk, user=request.user.username); comment.save() return HttpResponseRedirect(reverse('articles:comments', args=(comment.article_id)))
def post(self, request, article_id): comment = Comment() user = UserFree() content = request.POST.get('content', '') nickname = request.POST.get('nickname', '') email = request.POST.get('email', '') if nickname == '' or email == '': user.nickname = '匿名用户' user.email = '' else: user.nickname = nickname user.email = email user.save() reply_comment_id = request.POST.get('reply_comment_id') if int(reply_comment_id) < 0: return HttpResponse('{"status":"fail", "msg":"回复出错"}', content_type='application/json') elif int(reply_comment_id) == 0: comment.parent = None comment.root = None comment.article_id = article_id comment.content = content comment.user = user comment.save() return HttpResponse('{"status":"success", "msg":"评论成功"}', content_type='application/json') elif int(reply_comment_id) > 0: parent = Comment.objects.get(id=int(reply_comment_id)) if parent: if parent.root is None: comment.root_id = parent.id else: comment.root_id = parent.root_id comment.article_id = article_id comment.parent = parent comment.content = content comment.reply_to = parent.user comment.user = user comment.save() return HttpResponse('{"status":"success", "msg":"回复成功"}', content_type='application/json') else: return HttpResponse('{"status":"fail", "msg":"回复出错"}', content_type='application/json')
class NotificationModelTest(TestCase): def setUp(self): self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.user_2 = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.article = Article.objects.create(title='Test', content="test content", user=self.user) self.comment = Comment(body='test', article=self.article, user=self.user) self.reply = Comment(body='test reply', article=self.article, parent=self.comment, user=self.user) self.article_like = ArticleLike(user=self.user_2, article=self.article) self.special_article_like = ArticleLike(special_like=True, user=self.user_2, article=self.article) self.follow = UserFollowing(user_follows=self.user, user_followed=self.user_2) def test_create_like_notification_via_signal(self): """ Creates a like notification via the signal. """ self.article_like.save() self.assertEqual(Notification.objects.count(), 1) self.assertEqual( str(Notification.objects.get()), f'{self.user_2.display_name} liked {self.article.title}') def test_create_special_like_notification_via_signal(self): """ Creates a special like notification via the signal. """ self.special_article_like.save() self.assertEqual(Notification.objects.count(), 1) self.assertEqual( str(Notification.objects.get()), f'{self.user_2.display_name} Special liked {self.article.title}') def test_create_comment_notification_via_signal(self): """ Creates a comment notification via the signal. """ self.comment.save() self.assertEqual(Notification.objects.count(), 1) self.assertEqual( str(Notification.objects.get()), f'{self.user.display_name} commented on {self.article.title}') def test_create_reply_notification_via_signal(self): """ Creates a reply notification via the signal. """ self.comment.save() self.reply.save() self.assertEqual(Notification.objects.count(), 3) self.assertEqual( str(Notification.objects.get(action=Notification.REPLY)), f'{self.user.display_name} replied to {self.reply.body}...') def test_create_follow_notification_via_signal(self): """ Creates a follow notification via the signal. """ self.follow.save() self.assertEqual(Notification.objects.count(), 1) self.assertEqual(str(Notification.objects.get()), f'{self.user.display_name} is now following you')
def handle(self, *args, **options): num_comments = 500 users = User.objects.filter(admin=False) articles = Article.objects.all() filter_words = Filter_Words.objects.all() content = open("dictionaries/comments").readlines() count = 0 for i in range(0, num_comments): comments = Comment.objects.all() c = Comment() c.user = random.choice(users) c.article = random.choice(articles) c.content = random.choice(content).rstrip() c.pub_date = timezone.now() for word in filter_words: if (re.search(str(word), c.content, re.IGNORECASE)): c.flag = True if (i > num_comments / 2): c.parent = random.choice(comments) c.article = c.parent.article c.save() count = i print(str(count) + " comments added")