def PostComment(request, pk): template_name = 'news/news_comment.html' post = get_object_or_404(News, id=pk) comments = Comment.objects.all().filter(news_id=pk).filter(approved='Y') new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) member = User.objects.all().filter( username=request.user.username).first() if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.news_id = pk if member: new_comment.name = member.first_name new_comment.approved = 'Y' # Save the comment to the database new_comment.save() else: print("Could not save comment by {}".format(request.user.username)) else: comment_form = CommentForm() return render( request, template_name, { 'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form })
def new_single(request, pk): # pk is id of article """ вызов полной сатьи и комментариев к ней """ new = get_object_or_404(News, id=pk) comment = Comments.objects.filter( new=pk ) # moderation=True) # все записи, где номер статьи = pk (и комментарии модерированы) if request.method == 'POST': form = CommentForm(request.POST) # пользователь уже ввел if form.is_valid(): # зная, кто на сайте и кто отправил форму, надо добавить юзера к модели комментариев form = form.save(commit=False) # Приостановили сохранение формы form.user = request.user # к полю форм.юзер присваиваем имя того, кто совершил запрос form.new = new # присвоим статью, на которой делали комментарий form.save() return redirect( new_single, pk ) # перенаправляем пользователя на изначальную страницу новости else: form = CommentForm() return render( request, "news/new_single.html", # передаем в ХТМЛ то, что в кавычках { "new": new, 'comments': comment, # выше первый метод вывода комментариев "form": form }) # потом перейти в УРЛ, который будет запускать эту функцию
def post_detail(request, pk): posts = Post.objects.all() post = get_object_or_404(Post, id=pk) comments_list = Comment.objects.filter(post=post).order_by('-id') paginator = Paginator(comments_list, 3) page = request.GET.get('page') try: comments = paginator.page(page) except PageNotAnInteger: comments = paginator.page(1) except EmptyPage: comments = paginator.page(paginator.num_pages) if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): content = request.POST.get('content') comment = Comment.objects.create(post=post, sender=request.user, content=content) comment.save() return HttpResponseRedirect(post.get_absolute_url()) else: comment_form = CommentForm() context = { 'posts': posts, 'post': post, 'comments': comments, 'comment_form': comment_form, 'pk': pk, 'object': post } return render(request, 'news/post_detail.html', context)
def add_comment(request, news): context = {} context.update(csrf(request)) if request.POST: form = CommentForm(request.POST) new = News.objects.get(slug=news) if form.is_valid(): comment = form.save(commit=False) comment.comments_user = request.user comment.comments_news_id = new.id comment.published_time = timezone.now() comment.save() return redirect('/news/' + news + '/') else: form = CommentForm() context['form'] = form context['creation_error'] = "Invalid information was entered." return render(request, 'add_comment.html', context) else: context['username'] = auth.get_user(request).username if (context['username']): user = User.objects.get(username=auth.get_user(request).username) context['C_M'] = is_CM(user) else: context['C_M'] = None context['form'] = CommentForm() context['news'] = news context['departments'] = departments return render(request, 'add_comment.html', context)
def add_comment_to_news(request, pk): news = get_object_or_404(News, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.news = news comment.save() return redirect('news:detail_news', pk=news.pk) else: form = CommentForm() return render(request, 'news/comment_form.html', {'form': form})
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 show(request, s_id): submission = get_object_or_404(Submission, pk=s_id) return render_to_response( 'show.html', {'submission': submission, 'form': CommentForm(initial={'submission': submission})}, context_instance=RequestContext(request) )
def post(self, request, content_id): form = CommentForm(request.POST) ip = request.META['REMOTE_ADDR'] if form.is_valid(): if request.user.id: restore = request.POST.get("restore", None) if restore: Comment.objects.create( user_id=request.user, news_id=Content.objects.get(id=content_id), content=request.POST.get("content"), restore=Comment.objects.get( id=request.POST.get("restore")), restore_user=UserInfo.objects.get( id=request.POST.get("restore_user")), ip=ip, ) else: Comment.objects.create( user_id=request.user, news_id=Content.objects.get(id=content_id), content=request.POST.get("content"), ip=ip, ) else: return HttpResponse("登陆后才能评论!") return redirect("/news/%s" % content_id)
def edit_comment(request: HttpRequest, comment_id: int): comment = get_object_or_404(Comment, id=comment_id) article: Article = comment.article if article.created_by != request.user: raise Http404 if request.method != 'POST': form = CommentForm(instance=comment) else: form = CommentForm(instance=comment, data=request.POST) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Comment updated successfully.') return redirect('news:article-detail', slug=article.slug) context = {'form': form, 'article': article, 'comment': comment} return render(request, 'news/edit-comment.html', context)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = NewsComment.objects.filter( news=super().get_object()) context['all_news'] = News.objects.all()[:20] context['comment_form'] = CommentForm() return context
def addcomment(request, article_id): return_path = request.META.get('HTTP_REFERER', '/') #Возврат на предыдущую страницу if request.POST: form = CommentForm(request.POST) #print('\n',form,'\n') if form.is_valid(): #Добавляем массив шаблона "Текст" в таблицу Комментарии #print(article) comment = form.save(commit=False) #print('\n',comment,'aaaaaaaaaa','\n') comment.articles = Articles.objects.get(id=article_id) #a = User.get_username(self) comment.author = request.user comment.date = timezone.now() form.save() #Увеличиваем кол-во сообщений в таблице Статьи. article = Articles.objects.get(id=article_id) comment = Comments.objects.filter(articles_id=article_id).count() article.comm = comment article.save() else: error = 'У вас невалидная форма сообщения' render(request, 'main/error.html', {'error': error}) else: error = 'У вас не отправились данные на сервер' render(request, 'main/error.html', {'error': error}) return redirect(return_path)
def addcomment(request, news_id): if request.POST: form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comments_news = News.objects.get(id=news_id) form.save() return redirect('/news/get/%s/' % news_id)
def edit_comment(request, s_id, c_id): comment = get_object_or_404(Comment, pk=c_id) submission = get_object_or_404(Submission, pk=s_id) if request.method == 'POST': form = CommentForm(request.POST, instance=comment) if form.is_valid(): c = form.save() return redirect(submission) else: return render_to_response('edit_comment.html', {'form': form, 'comment':comment}, context_instance=RequestContext(request)) return render_to_response('edit_comment.html', {'form': CommentForm(instance=comment), 'comment':comment}, context_instance=RequestContext(request) )
def new_single(request, pk): """ Вывод полной статьи """ new = get_object_or_404(News, id=pk) comment = Comments.objects.filter(new=pk, moderation=True) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.new = new form.save() return redirect(new_single, pk) else: form = CommentForm() return render(request, "news/new_single.html", {"new": new, "comments": comment, "form": form})
def post(self, request, *args, **kwargs): form = CommentForm(request.POST) pk = kwargs['pk'] post = get_object_or_404(Post, id=pk) if request.method == 'POST': if form.is_valid(): comm = form.save(commit=False) comm.post = post comm.author = request.user comm.save() comments = Comment.objects.filter(post_id=pk).order_by('-created_date') return render(request, 'post_detail.html', context={ 'post': post, 'comments': comments, 'form': CommentForm() })
def new(request, pk): new = get_object_or_404(News, id=pk) comments = Comments.objects.filter(new=pk, moderation=True) if request.POST: comm_form = CommentForm(request.POST) if comm_form.is_valid(): comm_form = comm_form.save(commit=False) comm_form.user = request.user comm_form.new = new comm_form.save() return redirect('/news/' + str(pk)) else: comm_form = CommentForm() return render(request, 'news/new.html', { 'new': new, 'comments': comments, 'comm_form': comm_form })
def get(self, request, content_id): types = Type.objects.all() data = Content.objects.get(id=content_id) data.clicked = int(data.clicked) + 1 data.save() form = CommentForm() comment_list = Comment.objects.filter(news_id=data, restore=None) hot_news = Content.objects.all().order_by("-clicked")[:10] return render(request, "news.html", locals())
def create_comment(request: HttpRequest, article_id) -> Union[HttpResponseRedirect, HttpResponsePermanentRedirect, HttpResponse]: """Create a new comment.""" article = get_object_or_404(Article, id=article_id) if article.created_by != request.user: raise Http404 if request.method != 'POST': form = CommentForm() else: form = CommentForm(data=request.POST) if form.is_valid(): new_comment: Comment = form.save(commit=False) new_comment.article = article new_comment.save() messages.add_message(request, messages.SUCCESS, 'Comment created successfully.') return redirect('news:article-detail', slug=article.slug) return render(request, 'news/create-comment.html', {'form': form, 'article': article})
def addСomment(request, article_id): if request.POST and ("pause" not in request.session): form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comments_articles = Articles.objects.get(id=article_id) form.save() request.session.set_expiry(60) request.session['pause'] = True return redirect('/news/' + str(article_id) + '/')
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) queryset = ArticleComment.objects.filter( article_id=self.object.id).all() page = self.request.GET.get('page') #ustawienie paginacji komentarzy context['comments'] = Paginator(queryset, 2).get_page(page) context['comments_number'] = ArticleComment.objects.filter( article_id=self.object.id).count() context['form'] = CommentForm() return context
def comment(request, s_id): submission = get_object_or_404(Submission, pk=s_id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): c = form.save() _update_session(request.session, 'comments', c) return redirect(submission) else: return render_to_response('show.html', {'submission': submission, 'form': form}, context_instance=RequestContext(request))
def get(request, *args, **kwargs): pk = kwargs['pk'] post = get_object_or_404(Post, id=pk) comments = Comment.objects.filter(post_id=pk).order_by('-created_date') return render(request, 'post_detail.html', context={ 'post': post, 'comments': comments, 'form': CommentForm() })
def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseRedirect(reverse('login')) else: comment_form = CommentForm(request.POST) if comment_form.is_valid(): NewsComment.objects.create( comment_text=comment_form.cleaned_data['comment_text'], news=super().get_object(), author=request.user) return super().get(self, request, *args, **kwargs)
def get(self, request, *args, **kwargs): news = self.get_object() comments_form = CommentForm() if request.user.is_authenticated: comments_form.fields['name'].widget = forms.HiddenInput() comments_form.initial['name'] = request.user.username return render(request, 'news/news_details.html', {'news_details': news, 'comments_form': comments_form} )
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 post_detail(request, year, month, day, slug): post = get_object_or_404(Post, slug=slug, status='published', published__year=year, published__month=month, published__day=day) comments = post.comments.filter(active=True) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.post = post new_comment.save() else: form = CommentForm() return render(request, 'news/post/detail.html', { 'post': post, 'comments': comments, 'form': form })
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 new_single(request, pk): """Вывод полной статьи """ new = get_object_or_404(News, id=pk) comment = Coments.objects.filter(new=pk, moderation=True) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid: # нам нужно присвоить к тому user который сейчас на сайте добавил коментарий form = form.save( commit=False) # для это пиостанавливаем сохранение form.user = request.user # присваиваем запросить пользователя который сейчас на сайте form.new = new form.save() # сохраняем нашу форму return redirect( new_single, pk) # чтоб вернулась страница с полем ввода комментария else: form = CommentForm() return render(request, 'new_singl.html', { 'new': new, 'comment': comment, 'form': form })
def post(self, request, *args, **kwargs): form = CommentForm({ "content": request.POST['comment'], "author": request.user, "news": self.get_object() }) if form.is_valid(): comment = form.save() if comment.news.author_id != comment.author_id: domain = get_current_site(self.request).domain send_informing_about_comment_email.delay( comment.news.author_id, comment.author_id, comment.news_id, domain) return redirect( reverse_lazy("news-detail", kwargs={"pk": self.get_object().pk}))
def serve(self, request, *args, **kwargs): # Add comment before calling get_context, so it's included if "comment" in request.POST: comment = request.POST["comment"] in_reply_to = request.POST.get("in_reply_to", None) Comment.objects.create( content=comment, author=request.user, news_page=self, parent_id=in_reply_to, ) context = self.get_context(request, **kwargs) context["comment_form"] = CommentForm() response = TemplateResponse(request, self.template, context) set_seen_cookie_banner(request, response) return response