Django制作博客中为文章添加评论

1.当用户在article_page.html中写完评论,点击Submit提交时,用post方法进入urls.py中,url=/focus/{{ article.id }}/comment/

html中评论表单代码:

<form action="/focus/{{ article.id }}/comment/" method="post" name="comment">
    {% csrf_token %}
    {{ commentform.as_p }}
     <input class="btn btn-default" type="submit" value="Submit" />
</form>

<!-- Comments -->
<h3>Comments:</h3>
<hr>
{% for comment in comments %}
<div class="row">

   <article class="col-xs-12">

      <p class="pull-right"> <span class="label label-default">tag</span> <span class="label label-default">{{ comment.user.first }}</span></p>

      <p>{{ comment.content }}</p>
   <!--   <p><button class="btn btn-default">Read More</button></p>  -->

      <ul class="list-inline">
         <li><a href=" ">{{ comment.pub_date | date:"j M" }}</a></li>
         <li><a><span class="glyphicon glyphicon-comment"></span> {{ comment.comment_num }} Comments</a></li>
         <li><a href="/focus/{{ comment.id }}/poll_comment"><span class="glyphicon glyphicon-thumbs-up"></span>{{ comment.poll_num }} Upvotes</a></li>
      </ul>
   </article>
</div>
<hr>
{% endfor %}

 

2.经过urls路由进入views.pycomment函数

url(r'^(?P<article_id>[0-9]+)/comment/$', views.comment, name='comment'),

其中r'^(?P<article_id>[0-9]+)是传入comment方法的参数article_id

3.调用models将用户名、表单CommentForm返回的评论、article_id存入数据库,获得article_id所对应的文章,文章对应数据库里面评论数+1

def comment(request, article_id):  # article_page.html中评论,将评论内容、用户名、文章id存入数据库
    form = CommentForm(request.POST)  # 得到类CommentFormTextarea里的评论内容,评论内容存在request.POST,创建了一个form表单
    # 只有当name=comment时才能form表单中才有评论
    # return HttpResponse(form)
    url = urlparse.urljoin('/focus/', article_id)
    if form.is_valid():
        logged_user = request.user  # 获取请求的用户对象
        article = Article.object.get(id=article_id)  # 获取文章idarticle_id的文章
        new_comment = form.cleaned_data['comment']  # 读取表单返回的值,返回类型为字典dict        # return HttpResponse(new_comment)
        c = Comment.objects.create(content=new_comment, article=article)
        # 增加子表数据时(article=article=article_id=article.id        # 将评论内容、文章id、用户存进数据库Comment表中
        # return HttpResponse(logged_user.username)
        c.user.add(logged_user)  # comment_user多对多表添加
        c.save()
        article.comment_num += 1  # 评论数加1
        article.save()
    return redirect(url)  # 返回当前页面(刷新)

 

4.重新获得url = "/focus/{{ article_id }}",查询urls,进入views.article

url(r'^(?P<article_id>[0-9]+)/$', views.article, name='article'),

5.从models中取出各种值,comments = article.comment_set.all,将这些值渲染进article_page.html中

6.通过上面的for函数将新的评论写进article_page.html网页中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值