我正在制作一个django博客,并希望显示每篇博文的评论列表,但我无法弄清楚如何在视图和模板中引用评论.我的模型定义如下:
class Issue(models.Model):
title = models.CharField(max_length=255)
text = models.TextField()
author = models.ForeignKey(User)
def __unicode__(self):
return self.title
class Comment(models.Model):
commenter = models.ForeignKey(User)
issue = models.ForeignKey(Issue)
text = models.TextField()
Run Code Online (Sandbox Code Playgroud)
我的观点是这样的
class IssueDetail(DetailView):
model = Issue
context_object_name = "issue"
template_name = "issue_detail.html"
def get_context_data(self, **kwargs):
context = super(IssueDetail, self).get_context_data(**kwargs)
context['comments'] = Comment.objects.all()
return context
class CommentDetail(DetailView):
model = Comment
context_object_name = "comment"
template_name = "comment_detail.html"
Run Code Online (Sandbox Code Playgroud)
最后是issue_detail.html模板
{% block content %}
<h2>{{ issue.title }}</h2>
<br/>
<i>As written by {{ issue.author.first_name }}</i>
<br/><br/>
<blockquote> {{ issue.text }}</blockquote>
<h3>Comments</h3>
{% for comment in comments %}
<li>{{comment}}</li>
{% endfor %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
这允许我引用Issue模板中注释的字段,但基本上我希望注释有一个自己的模板,它将在for循环中呈现.在Django中执行此操作的正确方法是什么?
该comments是你的模板已经可用,因为您定义的模型关系.你可以删除get_context_datain IssueDetail.
您的issue_detail.html模板可能如下所示:
{% for comment in issue.comment_set.all %}
{% include 'comment_detail.html' %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
您的comment_detail.html模板可能如下所示:
<ul>
<li>{{ comment.issue }}</li>
<li>{{ comment.text }}</li>
</ul>
Run Code Online (Sandbox Code Playgroud)