Example #1
0
File: views.py Project: 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
        })  # потом перейти в УРЛ, который будет запускать эту функцию
Example #2
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)
Example #3
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)
Example #4
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) + '/')
Example #5
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)
Example #6
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)
Example #7
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)
Example #8
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
        })
Example #9
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})
Example #10
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
    })
Example #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))
Example #12
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))
Example #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})
Example #14
0
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
    })
Example #15
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}))
Example #16
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)
            )
Example #17
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)
            )
Example #18
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()
                   })
Example #19
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})
Example #20
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
    })