Exemplo n.º 1
0
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
        })
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
 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)
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
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)
Exemplo n.º 6
0
Arquivo: views.py Projeto: 0ndreu/Blog
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
        })  # потом перейти в УРЛ, который будет запускать эту функцию
Exemplo n.º 7
0
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)
Exemplo n.º 8
0
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) + '/')
Exemplo n.º 9
0
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))
Exemplo n.º 10
0
 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)
Exemplo n.º 11
0
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))
Exemplo n.º 12
0
    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]))
Exemplo n.º 13
0
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})
Exemplo n.º 14
0
def add_comment(request, news_id):
    if request.user.is_authenticated():
        if request.user.is_active:
            if request.POST:
                form = CommentForm(request.POST)
                if form.is_valid():
                    comment = form.save(commit=False)
                    comment.comment_date = datetime.datetime.now()  # set tz =
                    comment.comment_likes = 0
                    comment.comment_news = News.objects.get(id=news_id)
                    comment.comment_user = request.user
                    form.save()
    return redirect('news.views.news', news_id=news_id)
Exemplo n.º 15
0
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)
Exemplo n.º 16
0
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)
Exemplo n.º 17
0
    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}))
Exemplo n.º 18
0
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)
            )
Exemplo n.º 19
0
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)
            )
Exemplo n.º 20
0
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
    })
Exemplo n.º 21
0
 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()
                   })
Exemplo n.º 22
0
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("/")
Exemplo n.º 23
0
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})
Exemplo n.º 24
0
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})
Exemplo n.º 25
0
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
    })
Exemplo n.º 26
0
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("/")