def save(self, commit=True): author = self.initial.get('author') to_post = self.cleaned_data.get('to_post') text = self.cleaned_data.get('text') comment = Comment(to_post=to_post, author=author, text=text) comment.save() return comment
def create_comment(request, **kwargs): data = request.POST news = get_object_or_404(News, pk=kwargs.get('pk')) feedback = data.get('feedback') comment_by = request.user payload = {"news": news, "comment_by": comment_by, "feedback": feedback} comment = Comment(**payload) comment.save() return render(request, "news/comment.html", {"comment": comment})
def comments(request, *args, **kwargs): print("I AM INSIDE VIEW", args, kwargs) template_name = "news/comment.html" comment = request.POST feedback = comment.get("feedback") news = get_object_or_404(News, pk=kwargs.get("news_id")) comment = Comment(feedback=feedback, commentor=request.user, news=news) comment.save() comments = Comment.objects.filter(news=news) return render(request, template_name, {"comments": comments})
def news_comment(request, news_id): comment_news = News.objects.filter(pk=news_id)[0] user = request.user content = request.POST.get('comment') comment = Comment() comment.news = comment_news comment.user = user comment.content = content comment.save() return redirect(reverse('news:news_detail', kwargs={'news_id': news_id}))
def news_feedback(request, *args, **kwargs): data = request.POST news_id = kwargs.get("pk") news = get_object_or_404(News, id=news_id) # comment = Comment.objects.create(news=news, feedback=data["feedback"], commenter=request.user) comment = Comment(news=news, feedback=data["feedback"], commenter=request.user) comment.save() template_name = "news/comments.html" return render(request, template_name, {"comment": comment})
def comment(requests): if requests.method == 'POST' and requests.user.is_authenticated(): article_id = requests.POST.get('article') content = requests.POST.get('content') if len(content) >= 1: new_obj = Comment( user=User.objects.get(username=requests.user.username), content=content, news=Article.objects.get(id=article_id)) new_obj.save() return HttpResponseRedirect('article/{}'.format(article_id))
def post(self, request, pk): news = self.get_object() comment_form = CommentForm(request.POST) if comment_form.is_valid(): new_comment = Comment(news=news, **comment_form.cleaned_data) if request.user.is_authenticated: new_comment.name = request.user.username else: new_comment.name = 'Аноним' new_comment.save() return HttpResponseRedirect(reverse('news_details', args=[pk]))
def news_detail(request, pk): story = Story.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 = {"story": story, "comments": comments, "form": form} return render(request, "news_detail.html", context)
def create_comment(request): try: news = News.objects.filter(deleted=False, slug__contains=request.data['slug'])[0] user = Token.objects.filter( key__contains=request.data['token'])[0].user # user = Token.objects.get(key=request.data['token'])[0].user if request.method == 'POST': comment = Comment(title=request.data['title'], text=request.data['text'], news=news, created_date_time=timezone.now(), user=user) comment.save() return Response({"comment": "create"}) except IndexError: return Response({"comment": "error"})
def comment_on_post(post, text, attachment=None): if not text: raise ValueError("Text must be non-empty") graph = access_page() data = dict(message=text) if attachment is not None: data['attachment_url'] = attachment try: o = graph.put_object(post.fbid, 'comments', **data) except facebook.GraphAPIError as exn: if str(exn) == '(#2) Service temporarily unavailable': raise ServiceUnavailable() from exn else: logger.exception("GraphAPIError while posting to /%s/comments %r", post.fbid, data) raise p = Comment(post=post, fbid=o['id'], text=text) p.save() return p
def comment_list(request): if request.method == 'POST': data = request.DATA.copy() try: comment = Comment.objects.get( content_object__pk=data['content_object']) serializer = CommentSerializers(comment, data=data) except: comment = Comment( text=data['text'], content_object=Info.objects.get(id=data['content_object'])) serializer = CommentSerializers(data=data) if serializer.is_valid(): serializer.save() r = redis.StrictRedis(connection_pool=POOL) r.publish( 'comments', '[{"id":"%s", "comment":"%s"}]' % (data['content_object'], data['text'].strip())) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors)
def show_news(request, slug): try: news = News.objects.get(slug=slug) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): Comment(news=news, email=form.cleaned_data['email'], login=form.cleaned_data['login'], content=form.cleaned_data['content']).save() return redirect("/news/" + str(news.slug)) else: form = CommentForm() return render_to_response( 'news/show.html', { 'form': form, 'news': news, 'comments': news.comments.all().order_by('-date') }, context_instance=RequestContext(request)) except News.DoesNotExist: return redirect("/")
def post(self, request, pk): form = CommentForm(request.POST) post = self.get_object() if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.post = post comment.save() receiver = [post.author.email] sender = SENDER subject = 'Comment was added to your post' message = render_to_string( 'news/comment_added_notification_email.html', { 'post': post, 'comment': comment, }) if comment.author != post.author: send_email(subject, message, sender, receiver) return redirect('post_detail', pk=post.pk) else: comment = Comment() comment.description = request.POST.get('description') return render(request, 'news/create_comment.html', {'form': form})
def news_comment(): if not g.user: #判断用户是否登录 return jsonify(errno=Code.NODATA, errmsg="用户未登录!") news_id = request.json.get("news_id") content = request.json.get("comment") parent_id = request.json.get("parent_id") # print(news_id, content) if not all([news_id, content]): return jsonify(errno=Code.PARAMERR, errmsg="参数不全") # 取出新闻对象 try: news = News.query.get(news_id) except Exception as e: current_app.logger.error(e) return jsonify(errno=Code.DBERR, errmsg="获取新闻失败") if not news: return jsonify(errno=Code.NODATA, errmsg="新闻不存在") # 创建评论对象,设置属性 comment = Comment() comment.user_id = g.user.id comment.news_id = news_id comment.content = content if parent_id: comment.parent_id = parent_id # 保存评论 try: db.session.add(comment) db.session.commit() except Exception as e: current_app.logger.error(e) return jsonify(errno=Code.DBERR, errmsg="评论失败") return jsonify(errno=Code.OK, errmsg="评论成功", data=comment.to_dict())
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.news_id = id data.subject = form.cleaned_data['subject'] data.comment = form.cleaned_data['comment'] data.rate = form.cleaned_data['rate'] data.ip = request.META.get('REMOTE_ADDR') data.save() messages.success( request, "Yorumunuz başarı ile eklenmiştir. Teşekkür ederiz !") return HttpResponseRedirect(url) messages.warning( request, "Yorumunuz Gönderilememiştir, Lütfen Bilgilerinizi Kontrol Ediniz!") return HttpResponseRedirect(url)
news1 = News( author=test_user, title='Big Explosion', text= """The official told CNN that Trump's idea is to put something on the table to get Democrats to engage with negotiations. Trump is not expected to back down from his demand for a border wall, but the plan will seek to entice Democrats by offering other concessions. """, pub_date=timezone.now(), brief="Nobody knows!", image_address= 'https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Youth-soccer-indiana.jpg/1920px-Youth-soccer-indiana.jpg' ) news1.save() news1.tags.add(iran_tag, spain_tag, national_tag) news1_comment = Comment(author=test_user, text="Nice!", pub_date=timezone.now(), news=news1) news1_comment.save() news2 = News( author=test_user, title="Jones 'fit and ready' to face Rangers", text= """Kilmarnock manager Steve Clarke insists he will have no hesitation in playing Jordan Jones against Rangers on Wednesday. The 24-year-old winger signed a pre-contract agreement with Killie's title rivals last week and will join Rangers on a four-year contract in the summer. """, pub_date=timezone.now(), brief= "Kilmarnock manager Steve Clarke insists he will have no hesitation in playing Jordan Jones against Rangers on Wednesday.", image_address= 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSwABkJsTIpRNDyJCIVjEAhL20W7mhC6mg738GUsfTSIzmPoexx'
def handle(self, *args, **options): faker = Faker() # Create categories if Category.objects.all().count() == 0: Category.objects.bulk_create([ Category(name='Politics', slug='politics', seo_title='Politics - read online on Blog-News', seo_description='Last news of Politics ' 'from all world. ' 'Read online on Blog-News.'), Category(name='Finance', slug='finance', seo_title='Finance - read online on Blog-News', seo_description='Last news of Finance ' 'from all world. ' 'Read online on Blog-News.'), Category(name='Economics', slug='economics', seo_title='Economics - read online on Blog-News', seo_description='Last news of Economics ' 'from all world. ' 'Read online on Blog-News.'), Category(name='Sports', slug='sports', seo_title='Sports - read online on Blog-News', seo_description='Last news of Sports ' 'from all world. ' 'Read online on Blog-News.') ]) all_categories = Category.objects.all() list_category_name = [category.name for category in all_categories] all_users_is_staff = User.objects.all() list_all_users_is_staff = [ user.username for user in all_users_is_staff if user.is_staff ] for new_post in range(options['len']): post = Post() post.title = faker.sentence(nb_words=5, variable_nb_words=False).replace( '.', '') post.slug = f'{post.title}'.lower().replace(' ', '-').replace( '.', '') # noqa post.article = faker.text() # random Category post.category = Category.objects.get( name=choice(list_category_name)) # random user is_staff post.author = User.objects.get( username=choice(list_all_users_is_staff)) post.seo_title = f'{post.title} | ' \ f'Read online | Blog news'.replace('.', '') post.seo_description = f'{post.title} | Blog news.' post.save() # list for random posts all_posts = Post.objects.all() list_post_name = [post.id for post in all_posts] # create comments comment = Comment() comment.text = faker.text() # random Post comment.for_post = Post.objects.get(id=choice(list_post_name)) # random user is_staff comment.author = User.objects.get( username=choice(list_all_users_is_staff)) comment.save()
def create(self, validated_data): comment = Comment(author=self.context['user'], text=validated_data['text'], news=validated_data['news']) comment.save() return comment