예제 #1
0
def add_comment(request, article_id):
    if request.user.is_authenticated():
        a = Article.objects.get(id = article_id)

        if request.POST and request.POST.get("content", "").strip() != '':

            form = CommentForm(request.POST)

            if form.is_valid():
                c = form.save(commit=False)
                c.creation_date = timezone.now()
                c.article = a
                c.author = request.user
                c.save()

                return HttpResponseRedirect('/articles/get/%s' % article_id)
        else:
            form = CommentForm()

        args = {}
        args.update(csrf(request))

        args['article'] = a
        args['form'] = form

        return render_to_response('add_comment.html', args)
    else:
        return HttpResponseRedirect('/accounts/login')
예제 #2
0
def addcomment(request, article_id):
    if request.POST:
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.comments_article = Article.objects.get(id=article_id)
            form.save()
    return redirect('/articles/get/%s' % article_id)
예제 #3
0
def addcomment(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_article = Article.objects.get(id=article_id)
			form.save()
			request.session.set_expiry(60)
			request.session['pause'] = True
	return redirect('/articles/get/%s/'  % article_id)
예제 #4
0
def addcomment(request, id):
    if 'pause' not in request.session:
        article = get_object_or_404(Article, id=id)
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.article = article
            comment.save()
            request.session.set_expiry(60)  # кука с сессией будет актуальна 1 минуту
            request.session['pause'] = True # дополнительное значение в сессии
    return redirect('/articles/get/{}/'.format(id))
예제 #5
0
파일: views.py 프로젝트: russin-alers/Blogy
def addcomment(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_acticle = Article.objects.get(id = article_id)
            comment.comments_date = datetime.datetime.now()
            form.save()
            request.session.set_expiry(3)
            request.session['pause'] = True

    return redirect("/get/%s" % article_id)
예제 #6
0
파일: views.py 프로젝트: voolf00/kino
def addComment (request, article_id):
    if request.POST:
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)# запрещаем сохранять сейчас
            comment.comments_article = Article.objects.get(id = article_id)
            comment.comments_user_id = auth.get_user(request).id
            comment.comments_date = datetime.datetime.today()
            form.save()
            #request.session.set_expiry(1)
            #request.session['pouse'] = True
    return redirect('/articles/get/%s' % article_id)
예제 #7
0
 def post(self, request, *args, **kwargs):
     if 'pause' not in request.session:
         comment_form = CommentForm(request.POST)
         if comment_form.is_valid():
             comment = comment_form.save(commit=False)
             comment.article = Article.objects.get(pk=kwargs.get('pk'))
             comment.user = self.request.user
             comment_form.save()
             return JsonResponse({'status': 'success',
                                  'user': self.request.user.get_official_name(), })
         else:
             return JsonResponse({'status': 'error'})
예제 #8
0
def comment(request, article_id):
    art = Article.objects.get(id=article_id)
    if request.method == 'POST':
        form = CommentForm(data=request.POST)
        if form.is_valid():
            comm = form.save(commit=False)
            comm.comment_date = timezone.now()
            comm.article = art
            comm.save()
            messages.success(request, "Your Comment was added")
            return redirect('all_articles')
    else:
        form = CommentForm()
        args = {}
        args.update(csrf(request))
        args['article'] = art
        args['form'] = form
    return render(request, 'comment/comment.html', args)
예제 #9
0
파일: views.py 프로젝트: ashutoshm90/django
def add_comment(request, article_id):
    a = Article.objects.get(id=article_id)
    if request.method == 'POST':
        f = CommentForm(request.POST)
        if f.is_valid():
            c = f.save(commit=False)
            c.pub_date = timezone.now()
            c.article = a
            c.save()
            messages.success(request, "Your Comment was Added")
            return HttpResponseRedirect('/articles/get/%s' % article_id)
    else:
        f = CommentForm()
    args = {}
    args.update(csrf(request))
    args['article'] = a
    args['form'] = f
    return render_to_response('add_comment.html', args)
예제 #10
0
def add_comment(request, article_id):
    a = Article.objects.get(id=article_id)
    #print "Add Comment ......:",a
    if request.method == "POST":
        f = CommentForm(request.POST)
        #print "Add Comment :",f
        if f.is_valid():
            #print "In is valid ::::"
            c = f.save(commit=False)
            c.pub_date = datetime.now()
            c.article = a
            c.save()
            
            messages.success(request, "Your comment was added")
            return HttpResponseRedirect('/articles/get/%s'%article_id)
        
    else:
        f = CommentForm()
        
    args={}
    args.update(csrf(request))
    args['article'] = a
    args['form'] = f
    return render_to_response('add_comment.html',args)
예제 #11
0
def addcomment(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_author = request.user
            comment.comments_article = Article.objects.get(id=article_id)
            form.save()
            request.session.set_expiry(60)
            request.session['pause'] = True
    return redirect('/articles/get/%s/' % article_id)
예제 #12
0
def addcomment(request, article_id):
    if request.method=='POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.comments_article = Article.objects.get(id = article_id)
            if request.user.is_anonymous():
                return redirect('/article/get/%s/' % article_id)
            else:
                comment.comments_from = request.user
                form.save()
                return redirect('/article/get/%s/' % article_id)
예제 #13
0
파일: views.py 프로젝트: russin-alers/Blogy
def addcomment(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_acticle = Article.objects.get(id=article_id)
            comment.comments_date = datetime.datetime.now()
            form.save()
            request.session.set_expiry(3)
            request.session['pause'] = True

    return redirect("/get/%s" % article_id)
예제 #14
0
def addcomment(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_article = Article.objects.get(id=article_id)
            comment.comments_article_id = article_id
            form.save()
            # сессия существует в течении 60 сек
            request.session.set_expiry(60)
            request.session['pause'] = True
    return redirect('/articles/get/%s/' % article_id)
예제 #15
0
def detail(request, id):
    post = Article.objects.get(id=id)
    all_comment = Comment.objects.filter(article__id=id)
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.post = post
            new_comment.save()
    else:
        comment_form = CommentForm()
    return render(request, 'detail.html', {'post': post, 'all_comment': all_comment, 'comment_form': comment_form})
예제 #16
0
def article(request, slug):
    if request.method == "POST":
        comment_form = CommentForm(data=request.POST)
        user = comment_form.save().author
        if comment_form.is_valid() and user.is_authenticated():
            Article.objects.get(slug=slug).comments.add(comment_form.save())

        else:
            return HttpResponse("You are not allowed to comment")

    else:
        comment_form = CommentForm()

    return render(request, 'article.html',
            {'article':Article.objects.get(slug=slug),'comment':comment_form,
                'request':request })
예제 #17
0
def addcomment(request, article_id):  # добавление комментариев

    if request.POST:
        form = CommentForm(request.POST)
        username = auth.get_user(request).username

        if form.is_valid():
            comment = form.save(commit=False)
            comment.comments_article = Article.objects.get(id=article_id)
            comment.username_comments = request.user
            form.save()

    return redirect('/articles/get/%s/' % article_id)
예제 #18
0
def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('post_detail', pk=post.pk)

    else:
        form = CommentForm()
    return render(request, 'comment_form.html', {'form': form})
예제 #19
0
def article_detail(request, id, slug):
    article = get_object_or_404(ArticlePost, id=id, slug=slug)
    # total_views = r.incr("article:{}:views".format(article.id))
    # import redis
    # from django.conf import settings
    # 注:用redis统计文章访问量较快,大型网站常用。此处个人博客不用,省的每次开redis服务器
    # r = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)
    # r.zincrby('article_ranking', 1, article.id)  # 每次访问时,自增article_ranking里对应article_id的分数

    # 按照索引范围获取name对应的有序集合的元素,0~-1表示从开头到结尾,排序规则desc=True表示从大到小
    # article_ranking = r.zrange("article_ranking", 0, -1, desc=True)[:10]
    # article_ranking_ids = [int(id) for id in article_ranking]  # 对字典而言,直接for的话取的是key

    # most_viewed = list(ArticlePost.objects.filter(id__in=article_ranking_ids))  # id__in可以传进列表一次取值
    # most_viewed.sort(key=lambda x: article_ranking_ids.index(x.id))  # 用id排序

    if request.method == "POST":
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.article = article
            new_comment.save()
    else:
        comment_form = CommentForm()  # get方法的话,直接创建表单返回
        article.views += 1
        article.save(update_fields=['views'])  # 存进数据库

    most_viewed_articles = ArticlePost.objects.all().order_by(
        '-views')[:4]  # 以views数量降序排序

    article_tags_ids = article.article_tag.values_list(
        "id", flat=True)  # 得到当前对象(article_tag是一个对象)的指定字段值
    # exclude排除id相同的文章
    similar_articles = ArticlePost.objects.filter(
        article_tag__in=article_tags_ids).exclude(id=article.id)
    # 聚合,取4篇相似文章,依照最新和相同标签两种排序方式
    similar_articles = similar_articles.annotate(
        same_tags=Count("article_tag")).order_by('-same_tags', '-created')[:4]

    # return render(request, "article/list/article_content.html",
    # {"article": article, "total_views": total_views,
    # "most_viewed": most_viewed, "comment_form": comment_form, "similar_articles": similar_articles})
    return render(
        request, "article/list/article_content.html", {
            "article": article,
            "total_views": article.views,
            "most_viewed_articles": most_viewed_articles,
            "comment_form": comment_form,
            "similar_articles": similar_articles
        })
예제 #20
0
def article_detail(request, username, article_id, **kwargs):
    article = Article.objects.filter(id=article_id, author__username=username)
    if not article:
        return HttpResponseNotFound()
    content = markdown(article[0].content)
    # 历史纪录
    history_time_list, new_history = get_or_set_history(request, article[0].id)
    comment_form = CommentForm()
    comment_list = article[0].comment_set.all().order_by('create_time')[:5]
    total_comment_count = article[0].comment_set.count()
    response = render(request, 'article/article_detail.html', {
        'article': article[0],
        'content': content,
        'history_time_list': history_time_list,
        'tool_bar': kwargs.get('tool_bar'),
        'comment_form': comment_form,
        'comment_list': comment_list,
        'total_comment_count': total_comment_count,
    })
    response.set_cookie('history', new_history)
    return response
예제 #21
0
def add_comment(request, pk):
    user = request.user
    article = get_object_or_404(Article, pk=pk)
    if request.method == "POST" and (
            user.groups.filter(name="Users").count()
            or user.groups.filter(name="Authors").count()):
        form = CommentForm(request.POST)
        if form.is_valid():
            commentary = form.save(commit=False)
            commentary.article = article
            commentary.nick = user.profile
            commentary.save()
            return redirect('detail', pk=article.pk)
    else:
        form = CommentForm()
    return render(request, 'article/commentary_form.html', {'form': form})
예제 #22
0
def comment(request, article_id):
    art = Article.objects.get(id=article_id)
    if request.method == 'POST':
        form = CommentForm(data=request.POST)
        if form.is_valid():
            comm = form.save(commit=False)
            comm.comment_date = timezone.now()
            comm.article = art
            comm.save()
            messages.success(request, "Your Comment was added")
            return redirect('all_articles')
    else:
        form = CommentForm()
        args = {}
        args.update(csrf(request))
        args['article'] = art
        args['form'] = form
    return render(request, 'comment/comment.html', args)
예제 #23
0
def add_comment(request, article_id):
    """
    The function adds comment of the article
    :param request:
    :param article_id:
    :return:
    """
    if request.POST and ('pause' not in request.session):
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.comments_article = Article.objects.get(id=article_id)
            comment.comments_date = timezone.now()

            if request.user.id:
                comment.comments_from_id = request.user.id
            else:
                return HttpResponse('Не авторизован')

            form.save()
            # Создаем объект сессии в течении 60 секунд
            # request.session.set_expiry(60)
            # request.session['pause'] = True
    return redirect(reverse('article:article', args=(article_id, 1)))
예제 #24
0
def add_comments_view(request):
    """
    添加评论
    """
    form = CommentForm(request.POST)
    if not form.is_valid():
        return http_response(request, statuscode=ERRORCODE.PARAM_ERROR)

    nickname = form.cleaned_data.get('nickname')
    email = form.cleaned_data.get('email')
    website = form.cleaned_data.get('website')
    content = form.cleaned_data.get('content')
    target = form.cleaned_data.get('target')
    parent_comment_id = form.cleaned_data.get('parent_comment_id')

    try:
        user, created = Visitor.objects.update_or_create(
            nickname=nickname,
            email=email,
            defaults={
                "nickname": nickname,
                "email": email,
                "website": website,
                "avatar": gravatar_url(email)
            })
        ip_address = get_clientip(request)
        country, province, city = get_location_by_ip(ip_address)
        anchor = ''.join(
            random.sample(string.ascii_lowercase + string.digits, 16))
        comment_data = {
            "user_id": user.id,
            "content": content,
            "target": target,
            "ip_address": ip_address,
            "country": country,
            "province": province,
            "city": city,
            "anchor": anchor,
        }
        # 二级回复
        if parent_comment_id:
            parent_comment = Comments.objects.select_related().filter(
                pk=parent_comment_id).first()
            reply_to = parent_comment.user if parent_comment else None
            comment_data.update({
                "parent_id": parent_comment_id,
                "reply_to": reply_to
            })
            mail_body = MailTemplate.notify_parent_user.format(
                parent_user=parent_comment.user.nickname,
                parent_comment=parent_comment.content,
                comment_user=nickname,
                comment=content,
                target_url=DOMAIN_NAME + parent_comment.target,
                anchor='#' + parent_comment.anchor)
            send_email_task.delay(reply_to.email, mail_body)
        Comments.objects.create(**comment_data)
        cache.delete_pattern(target)  # 清除缓存
        if not parent_comment_id and not user.blogger:
            mail_body = MailTemplate.notify_blogger.format(
                nickname=nickname,
                comment=content,
                target_url=DOMAIN_NAME + target,
                anchor='#' + anchor)
            send_email_task.delay(BLOGGER_EMAIL, mail_body)
        return http_response(request, statuscode=ERRORCODE.SUCCESS)
    except Exception as exp:
        return http_response(request, statuscode=ERRORCODE.FAILED, msg=exp)