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


1410 浏览 5 years, 11 months

13 Generic Foreign Key 3

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

Comments的model变了之后,comments的视图和模板也需要改变了

修改视图,传递comments内容

from django.contrib.contenttypes.models import ContentType
from comments.models import Comment
def post_detail(request, slug=None):
    content_type = ContentType.objects.get_for_model(Post)
    obj_id = instance.id
    comments = Comment.objects.filter(content_type=content_type,object_id=obj_id)   
    context = {
        "title" : instance.title,
        "instance" : instance,
        "share_string":share_string,
        "comments":comments,
    }
    return render(request, "post_detail.html",context)  

删除原来的模板内容{{instance.comment_set.all}}替换为新模板

<p>Comments</p>
{% for comment in comments %}
{{comment.content_object}}
<div class="">
    {{comment.content}}
    <br/>
    via {{comment.user }} | {{comment.timestamp|timesince}} ago
</div>
{% endfor %}

{{comment.content_object}}可以灵活的显示关联的对象的内容,在评论显示部分,对应的用户,内容,时间戳都可以相应的显示出来。