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.py的comment函数
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) # 得到类CommentForm中Textarea里的评论内容,评论内容存在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) # 获取文章id为article_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网页中