Django - 如何使用_set.all设置for循环?

时间:2015-04-19 18:55:48

标签: python django django-templates

我正在试图弄清楚如何设置for循环;但是,我不确定如何正确设置它。如何正确设置for循环以在我的数据库中显示所有存储的值?

现在,在我的模板中,我将其设置为:

{% if comments %}
    {% for comments in post.comments_set.all %}
        {{ comments }}
    {% endfor %}
{% endif %}

{{comments}}没有值回报;但是,当{{comments}}放在循环之外时,它会返回第一个注释。

以下是我的views.py:

class PostList(generic.ListView):
    template_name = 'articles/index.html'
    context_object_name = "news_posts"
    paginate_by = 5

    def get_queryset(self):
        return newspost.objects.order_by('-post_date')[:5]

class PostComments(generic.DetailView):
    model = newspost
    context_object_name = "comments"
    template_name = 'articles/comments.html'

models.py:

def get_upload_file_name(instance, filename):
    return "img/%s_%s" % (str(time()).replace('.','_'), filename)

class newspost(models.Model):
    post_title = models.CharField(max_length=30)
    post_image = models.FileField(upload_to=get_upload_file_name, null=True)
    post_date = models.DateTimeField('Date Published')
    post_short_description = models.TextField(max_length=300)
    post_text = models.TextField()
    def __str__(self):
            return self.post

class PostComments(models.Model):
    post = models.ForeignKey(newspost)
    comments_count = models.IntegerField(default=0)
    comments_text = models.TextField(max_length=200, blank=True)
    def __str__(self):
            return self.comment_text

urls.py

urlpatterns = patterns('',

    url(r'^$', views.PostList.as_view(), name='index'),
    url(r'^(?P<pk>\d+)/$', views.PostDetail.as_view(), name='post'),
    url(r'^comments/(?P<pk>\d+)/$', views.PostComments.as_view(), name='comments'),
    url(r'^editors_request_form/$', views.EditorsRequestForm, name='editors')
)

我似乎无法找到设置for循环的正确方法,我尝试过多种东西,但似乎没有任何效果。那么如何设置我的for循环以返回我的所有{{comments}}?

1 个答案:

答案 0 :(得分:0)

模板中包含Post对象的变量的名称为object。 此外,在为其赋值之前,无法测试comments变量的存在。

您想要做的是:

{% for comments in object.comments_set.all %}
    {{ comments }}
{% endfor %}

如果没有注释,则不会呈现任何内容,因为循环将为空。您可以使用empty clause来处理没有评论的情况。例如:

{% for comments in object.comments_set.all %}
    {{ comments }}
{% empty %}
    The post has no comments.
{% endfor %}