博客五部曲之二 - 高级博客


1191 浏览 5 years, 3 months

18 评论线程

版权声明: 转载请注明出处 http://www.codingsoho.com/

给评论线程添加一个专门的视图,这样需要时可以将它分享。

首先创建url,并在跟URL里面包含它

urlpatterns = [
    url(r'^(?P<id>\d+$)', comment_thread, name="thread"),    
]

url(r'^comments/', include("comments.urls",namespace="comments")),

创建视图处理函数

def comment_thread(request, id):
    obj = get_object_or_404(Comment, id=id)
    initial_data = {
        "content_type": obj.content_type, #content_object.get_content_type,
        "object_id":obj.id, #content_id
    }
    form = CommentForm(request.POST or None, initial=initial_data)
    if form.is_valid():
        c_type = form.cleaned_data.get("content_type")
        content_type = ContentType.objects.get(model=c_type)
        obj_id = form.cleaned_data.get('object_id')
        content_data = form.cleaned_data.get('content')
        try:
            parent_id = int(request.POST.get("parent_id")) # not in form
        except:
            parent_id = None
        parent_obj = 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(obj.get_absolute_url())
    context = {
        "comment" : obj, 
        "form" : form
    }
    return render(request, "comment_thread.html", context)

大部分的内容都是从post_detail视图函数拷贝过来有几个不一样的地方

  1. 这儿的实例从Post对象变成了Comment
  2. 成功重定向时,改成了到Comment的详情视图,这儿用到了get_absolute_url,相应的需要在model里添加

添加comment_thread.html模板渲染评论信息,同样,参考了post_detail.html

<div class="row">
    <div class="col-sm-6 col-sm-offset-3">
        <p>{{comment.content}}</p>
            <footer>via {{comment.user }} | {{comment.timestamp|timesince}} ago | {% if comment.children.count > 0 %}{{comment.children.count}} Comment{% if comment.children.count > 1 %}s {% endif %}{% endif %}
            </footer>
            <div class="comment-reply-display">
                {% for child_comment in comment.children %}
                <blockquote>
                    <p>{{child_comment.content}}</p>
                    <footer>via {{child_comment.user }} | {{child_comment.timestamp|timesince}} ago</footer>
                </blockquote>
                {% endfor %}                   
                <form method="post" action="">{% csrf_token %}
                    {{form|crispy}}
                    <input type="hidden" name="parent_id" value="{{comment.id}}">
                    <input type="submit" value="Post Comments" class="btn btn-default">
                </form>
            </div>
    </div>
</div>

这儿有几点变化

  1. 之前的form默认是隐藏的,通过JQuery,而在线程评论页面,需要默认打开,可以删除class “comment-reply”或者改个名字
  2. 去掉了回复和线程评论这两个链接