Exemple #1
0
def update_comment(request):
    data = {}
    comment_form = CommentForm(request.POST, user=request.user)
    if comment_form.is_valid():
        # 检查通过,保存数据
        comment = Comment()
        comment.user = comment_form.cleaned_data['user']
        comment.text = comment_form.cleaned_data['text']
        comment.content_object = comment_form.cleaned_data['content_object']

        parent = comment_form.cleaned_data['parent']
        if parent:
            comment.root = parent.root if parent.root else parent
            comment.parent = parent
            comment.reply_to = parent.user
        comment.save()

        #评论/回复成功,返回数据
        data['status'] = 'SUCCESS'
        data['username'] = comment.user.get_nickname_or_username()
        data['comment_time'] = comment.comment_time.strftime(
            '%Y-%m-%d %H:%M:%S')
        data['text'] = comment.text
        data['reply_to'] = comment.reply_to.get_nickname_or_username(
        ) if parent else None
        data['id'] = comment.id
        data['root_id'] = comment.root.id if parent else None
        data['content_type'] = ContentType.objects.get_for_model(comment).model

    # 评论/回复失败
    else:
        data['status'] = 'ERROR'
        data['message'] = list(comment_form.errors.values())[0][0]
    return JsonResponse(data)
Exemple #2
0
def details(request, id):
    #instance = post.objects.get(id=1)
    instance = get_object_or_404(post, id=id)

    if instance.draft:
        if not request.user.is_authenticated():
            raise Http404
    initial_data = {
        "content_type": instance.get_content_type,
        "object_id": instance.id,
    }
    comment_form = CommentForm(request.POST or None, initial=initial_data)

    if comment_form.is_valid() and request.user.is_authenticated():
        c_type = comment_form.cleaned_data.get("content_type")
        content_type = ContentType.objects.get(model=c_type)
        obj_id = comment_form.cleaned_data.get("object_id")
        content_data = comment_form.cleaned_data.get("content")
        parent_obj = None
        try:
            parent_id = int(request.POST.get("parent_id"))
        except:
            parent_id = None

        if parent_id:
            parent_qs = Comment.objects.filter(id=parent_id)
            if parent_qs.exists() and parent_qs.count() == 1:
                parent_obj = parent_qs.first()

        new_comment, created = Comment.objects.get_or_create(
            user=request.user,
            content_type=content_type,
            object_id=obj_id,
            content=content_data,
            parent=parent_obj,
        )
        return HttpResponseRedirect(instance.get_absolute_url())
    form = PostForm(request.POST or None,
                    request.FILES or None,
                    instance=instance)
    comments = instance.comments  #comment.objects.filter_by_instance(instance)
    context = {
        "instance": instance,
        "title": instance.title,
        "comment": comments,
        "comment_form": comment_form,
        "form_e": form,
    }
    #print(instance.content)
    return render(request, 'details.html', context)
Exemple #3
0
def blog_datell(request, blog_id):
    blog = get_object_or_404(Blog, id=blog_id)
    read_cookie_key = read_once(request, blog)
    blog_content_type = ContentType.objects.get_for_model(blog)
    comments = Comment.objects.filter(content_type=blog_content_type,
                                      object_id=blog.id)
    likes = Like.objects.filter(content_type=blog_content_type,
                                object_id=blog.id)
    pervious_blog = Blog.objects.filter(
        last_updelete_time__gt=blog.last_updelete_time,
        is_delete=False).last()
    next_blog = Blog.objects.filter(
        last_updelete_time__lt=blog.last_updelete_time,
        is_delete=False).first()
    comment_form = CommentForm(initial={
        'content_type': blog_content_type.model,
        'object_id': blog_id
    })
    context = {
        "blog": blog,
        "pervious_blog": pervious_blog,
        "next_blog": next_blog,
        "comments": comments,
        "likes": likes,
        'comment_form': comment_form,
    }
    response = render(request, "blog/blog_datell.html", context)
    response.set_cookie(read_cookie_key, 'ture')
    return response
Exemple #4
0
def article_detail(request, id):
    #获取相应id的文章
    article = get_object_or_404(Article, id=id)

    #取出评论
    comment = Comment.objects.filter(article=id)

    #浏览量+1
    article.total_views += 1
    article.save(update_fields=['total_views'])
    #赋给上下文变量
    # 将markdown语法渲染成html样式
    md = markdown.Markdown(extensions=[
        # 包含 缩写、表格等常用扩展
        'markdown.extensions.extra',
        # 语法高亮扩展
        'markdown.extensions.codehilite',
        'markdown.extensions.toc',
    ])
    article.content = md.convert(article.content)
    comment_form = CommentForm()
    context = {
        'article': article,
        'toc': md.toc,
        'comments': comment,
        'comment_form': comment_form,
    }

    return render(request, 'article/detail.html', context)
 def post(self, request, id=None, *args, **kwargs):
     if id is not None:
         post_instance = get_object_or_404(Post, pk=id)
         initial_data = {
             'content_type': post_instance.get_content_type(),
             'object_id': post_instance.id
         }
         comment_form = CommentForm(request.POST)
         if request.user.is_authenticated:
             if comment_form.is_valid():
                 my_comment = comment_form.save(commit=False)
                 my_comment.user = request.user
                 my_comment.save()
                 messages.success(request, 'Comment Created Successfully.')
                 return redirect('postDetail', id=post_instance.pk)
     return render(request, self.template_name, self.context)
Exemple #6
0
def blog_detail(request, blog_pk):
    blog = get_object_or_404(Blogs, pk=blog_pk)
    blog_content_type = ContentType.objects.get_for_model(blog)
    comments = Comment.objects.filter(content_type=blog_content_type,
                                      object_id=blog_pk,
                                      parent=None)

    if not request.COOKIES.get('blog_{}_read'.format(blog_pk)):
        blog.read_num += 1
        blog.save()

    context = {}
    context['blog'] = blog
    context['user'] = request.user
    context['previous_blog'] = Blogs.objects.filter(
        pub_date__gt=blog.pub_date).last()
    context['next_blog'] = Blogs.objects.filter(
        pub_date__lt=blog.pub_date).first()
    context['comments'] = comments.order_by('-comment_time')
    context['comment_form'] = CommentForm(
        initial={
            'content_type': blog_content_type,
            'object_id': blog_pk,
            'reply_comment_id': 0
        })
    response = render(request, 'blog/blog_detail.html', context)

    response.set_cookie(
        key='blog_{}_read'.format(blog_pk),
        value='true',
    )
    return response
Exemple #7
0
def get_comment_form(obj):
    content_type = ContentType.objects.get_for_model(obj)
    return CommentForm(
        initial={
            'content_type': content_type.model,
            'object_id': obj.id,
            'reply_comment_id': 0
        })
Exemple #8
0
def get_comment_form(obj):
    content_type = ContentType.objects.get_for_model(obj)
    form = CommentForm(
        initial={
            'content_type': content_type.model,
            'object_id': obj.pk,
            'reply_comment_id': '0'
        })
    return form
Exemple #9
0
def update_comment(request):
    referer = request.META.get('HTTP_REFERER', reverse('blog:index'))
    comment_form = CommentForm(request.POST, user=request.user)

    if comment_form.is_valid():
        # 检查通过,保存数据
        comment = Comment()
        comment.user = comment_form.cleaned_data['user']
        comment.text = comment_form.cleaned_data['text']
        comment.content_object = comment_form.cleaned_data['content_object']

        parent = comment_form.cleaned_data['parent']
        if not parent is None:
            comment.root = parent.root if not parent.root is None else parent
            comment.parent = parent
            comment.reply_to = parent.user
        comment.save()
    return redirect(referer + '#comment')
Exemple #10
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     form = CommentForm()
     self.object.increase_views()
     self.object.body = markdown.markdown(self.object.body,
                                      extensions=['markdown.extensions.extra', 'markdown.extensions.codehilite',
                                                  'markdown.extensions.toc', ])
     comment_list = self.object.comment_set.all()
     context.update({'form': form, 'comment_list': comment_list})
     return context
Exemple #11
0
def post_comment(request, article_id):
    article = get_object_or_404(Article, id=article_id)

    # 处理 POST 请求
    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            content = request.POST["body"]
            print(content)
            ai = article.id
            ui = request.user.id
            Comment.objects.create(body=content,
                                   article_id=ai,
                                   CommentUser_id=ui)
            return redirect(article)
        else:
            return HttpResponse("表单内容有误,请重新填写。")
    # 处理错误请求
    else:
        return HttpResponse("发表评论仅接受POST请求。")
Exemple #12
0
def post_comment(request, pk):
    article = 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 = article
            comment.save()
            return redirect(article)
        else:
            comment_list = article.comment_set.all()
            context = {
                'comment_list': comment_list,
                'article': article,
                'form': form
            }
            return render(request, 'blog/index.html', context=context)
    else:
        redirect(article)
 def get(self, request, id=None, *args, **kwargs):
     if id is not None:
         post_instance = get_object_or_404(Post, pk=id)
         initial_data = {
             "content_type": post_instance.get_content_type(),
             "object_id": post_instance.id
         }
         comment_form = CommentForm(None, initial=initial_data)
         self.context['post'] = post_instance
         self.context['comment_form'] = comment_form
     return render(request, self.template_name, self.context)
def save_comment(request):
    
    err = True
    
    comment_status = 0
    
    try:
        if request.POST['private_comment']:
            comment_status = -2
    except:
        pass

    try:
        form = CommentForm(request.POST)
        comment = form.save(commit=False)
        comment.ip = request.META.get('REMOTE_ADDR', '')
        comment.created = datetime.today()
        comment.status = comment_status
        comment.save()
        
        err = False
        
        if comment_status == -2 or settings.COMMENT_NOTIFICATION_EMAIL:
            send_mail( _('Comment')+': '+comment.name, comment.comment, comment.email, [settings.COMMENT_NOTIFICATION_EMAIL], fail_silently=True)
        
    finally:
    
        if request.POST.get('ret'):
            ret = request.POST.get('ret')
        elif request.META.get('HTTP_REFERER'):
            ret = request.META.get('HTTP_REFERER')
        else:
            ret = '/'
       
        if err:
            ret += '?err=1'
            
        return HttpResponseRedirect(ret)
Exemple #15
0
def update_comment(request):
    referer = request.META.get('HTTP_REFERER', reverse('blog:index'))
    comment_form = CommentForm(request.POST, user=request.user)

    if comment_form.is_valid():
        # Check passed, save data
        comment = Comment()
        comment.user = comment_form.cleaned_data['user']
        comment.text = comment_form.cleaned_data['text']
        comment.content_object = comment_form.cleaned_data['content_object']
        parent = comment_form.cleaned_data['parent']

        if not parent is None:
            comment.root = parent.root if not parent.root is None else parent
            comment.parent = parent
            comment.reply_to = parent.user
        comment.save()

        # # Send notification
        # # Determine whether the comment is a blog or
        # if comment.reply_to is None:
        #     # 接受者是文章
        #     recipient = comment.content_object.get_user()
        #     if comment.content_type.model == 'post':
        #         blog = comment.content_object
        #         verb = '{0} 评论了你的《{1}》'.format(comment.user,blog.title)
        #     else:
        #         raise Exception('不明评论')
        #
        # else:
        #     # 接受者是作者
        #     recipient = comment.reply_to
        #     verb = '{0} 评论了你的评论{1}'.format(comment.user, strip_tags(comment.parent.text))
        #
        # notify.send(comment.user, recipient=recipient, verb=verb, action_object=comment)

    return redirect(referer + '#comment')
Exemple #16
0
def detail(request, id):  # 查看文章详情
    try:
        post = Article.objects.get(id=str(id))
        post.viewed()  # 更新浏览次数
        tags = post.tags.all()  # 获取文章对应所有标签
        form = CommentForm()
        comments = post.comment_set.all()
    except Article.DoesNotExist:
        raise Http404
    return render(request, 'post.html', {
        'post': post,
        'tags': tags,
        'form': form,
        'comments': comments
    })
    def get_context_data(self, **kwargs):
        articleid = int(self.kwargs[self.pk_url_kwarg])
        comment_form = CommentForm()
        user = self.request.user

        article_comments = self.object.comment_list()

        kwargs['form'] = comment_form
        kwargs['article_comments'] = article_comments
        kwargs['comment_count'] = len(
            article_comments) if article_comments else 0

        kwargs['next_article'] = self.object.next_article
        kwargs['prev_article'] = self.object.prev_article

        return super(ArticleDetailView, self).get_context_data(**kwargs)
Exemple #18
0
def create(request):
    if request.method == 'GET':
        form = CommentForm()
    elif request.method == 'POST':
        form = CommentForm(request.POST, request.FILES)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.created = timezone.now()
            comment.save()
            return render(request, 'create_success.html')
    return render(request, 'create.html', context={
        'form': form})
Exemple #19
0
def edit(request, id=None):
    comment = get_object_or_404(Comment, pk=id)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.published_date = timezone.now()
            comment.save()
            return redirect('/comments')
    else:
        form = CommentForm(instance=comment)
    return render(request, 'edit.html', {'form': form})
Exemple #20
0
def article_detail(request, id=None):
    article = get_object_or_404(ArticlePost, id=id)
    article.total_view += 1
    # filter 相当于 SQL 中的 where 语句
    comments = Comment.objects.filter(article=id)
    # print(comments)
    # update_fields    指明更新字段
    article.save(update_fields=['total_view'])
    md = markdown.Markdown(extensions=[
        'markdown.extensions.extra', 'markdown.extensions.codehilite',
        'markdown.extensions.toc'
    ])
    article.body = md.convert(article.body)
    comment_form = CommentForm()
    context = {
        'article': article,
        'toc': md.toc,
        'comments': comments,
        'comment_form': comment_form
    }
    return render(request, 'article/detail.html', context)
Exemple #21
0
def article_detail(request, article_id):
    """显示单个文章"""
    article_all = Article.objects.all().order_by('-created_time')
    article_list3 = article_all[0:3]
    category_list = Category.objects.all()
    tag_list = Tag.objects.all()
    article = Article.objects.get(id=article_id)
    previous_article = Article.objects.filter(
        created_time__gt=article.created_time).last()
    next_article = Article.objects.filter(
        created_time__lt=article.created_time).first()
    #评论相关
    article_content_type = ContentType.objects.get_for_model(article)
    comments = Comment.objects.filter(content_type=article_content_type,
                                      object_id=article.id)
    data = {}
    data['content_type'] = article_content_type.model
    data['object_id'] = article_id
    context = {
        'article': article,
        'previous_article': previous_article,
        'next_article': next_article,
        'article_list3': article_list3,
        'category_list': category_list,
        'tag_list': tag_list
    }
    context['comment_form'] = CommentForm(initial=data)
    context['comments'] = comments
    if not request.COOKIES.get('article_%s_read' % article_id):
        if ReadNum.objects.filter(article=article).count():  # 判断对应博客的记录是否存在
            #  存在记录
            readnum = ReadNum.objects.get(article=article)  # 取出数量
        else:
            # 不存在记录
            readnum = ReadNum(article=article)  # 实例化
        readnum.read_num += 1
        readnum.save()
    render_x = render(request, 'blog0315/article_detail.html', context)
    render_x.set_cookie('article_%s_read' % article_id, 'true')
    return render_x
Exemple #22
0
def blog_detail(request, blog_pk):  # 博客阅读页面
    blog = get_object_or_404(Blog, pk=blog_pk)
    blog_content_type = ContentType.objects.get_for_model(blog)
    comments = Comment.objects.filter(content_type=blog_content_type,
                                      object_id=blog.pk)
    if not request.COOKIES.get('blog_%s_read_num' % blog_pk):
        blog.read_num += 1
        blog.save()
    context = {}
    context['blog'] = blog
    context['comments'] = comments
    context['blog_on'] = Blog.objects.filter(
        created_time__gt=blog.created_time).last()
    context['blog_next'] = Blog.objects.filter(
        created_time__lt=blog.created_time).first()
    context['comment_from'] = CommentForm(initial={
        'content_type': blog_content_type.model,
        'object_id': blog_pk
    })
    response = render(request, 'blog_detai.html', context)  ####
    response.set_cookie('blog_%s_read_num' % blog_pk, 'true')
    return response
Exemple #23
0
    def get(self, request, topic_id):
        topic = LearningContent.objects.get(lnum=topic_id)
        topic.content = markdown.markdown(topic.content,
                                          extensions=[
                                              'markdown.extensions.extra',
                                              'markdown.extensions.codehilite',
                                              'markdown.extensions.toc',
                                          ])

        log = LearningContent.objects.get(lnum=topic_id)
        result = log.users_like.filter(username=request.user)
        comment_form = CommentForm()
        comment = Comment.objects.filter(learning_log=topic_id)
        flag = False
        if result:
            flag = True

        content = {
            'topic': topic,
            'flag': flag,
            'comment_form': comment_form,
            'comment': comment
        }
        return render(request, 'topic.html', content)
Exemple #24
0
def comment_block(target):
    return {
        "target": target,
        "comment_form": CommentForm(),
        "comment_list": Comment.get_by_target(target),
    }
Exemple #25
0
def comment_block(target):
    return {
        'target': target,
        'comment_form': CommentForm(),
        'comment_list': Comment.get_by_target(target)
    }
Exemple #26
0
def load_comment_form(article):
    content_type = ContentType.objects.get_for_model(article)
    comment_form = CommentForm(initial={'content_type': content_type.model, 'object_id': article.pk, 'reply_comment_id': '0'})
    return  {'comment_form':comment_form}