【发布时间】:2014-02-23 00:41:33
【问题描述】:
我正在制作一个 django 博客,并希望为每篇博客文章显示一个 cmets 列表,但我无法弄清楚如何在视图和模板中引用 cmets。 我的模型是这样定义的:
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()
我的观点是这样的
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"
最后是 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 %}
这允许我引用问题模板中的注释字段,但基本上我希望 cmets 拥有自己的模板,该模板将在 for 循环中呈现。在 Django 中执行此操作的正确方法是什么?
【问题讨论】: