【问题标题】:Django: For loop in tag displaying different informationDjango:标签中的For循环显示不同的信息
【发布时间】:2012-04-04 12:36:55
【问题描述】:

我遇到了这个问题:假设您有一个博客应用程序,并且您想要显示所有创建的帖子。但是您的帖子可以是“粘性”或“特色”,必须首先显示并且必须位于不同的 html“块”中。也许这不是最好的例子,但毕竟是我需要的。

所以,模型很简单:

class Post(models.Model):
  title = models.CharField()
  content = models.TextField()
  featured = models.BooleanField(default=False)
  created = models.DateTimeField(auto_now=False, auto_now_add=True)
  class Meta:
    ordering = ['-featured','-created']

在视图中,我只是查询所有帖子并将其显示在模板中:

def my_view(request):
  return render_to_response('template.html',{'posts':Post.objects.all()})

现在,问题出在我的模板中,我想要的结果是:

<html>
  <div class='featured-posts'>
     <ul>
      <li> A Featured post</li>
     </ul>
  </div>
  <div class='not-featured-posts'>
     <ul>
      <li> A NON Featured post</li>
     </ul>
  </div>
</html>

我能做什么?我在想也许我可以这样抓住那些分开的:

return render_to_response('template.html',{
  'featured':Post.objects.filter(featured=True),
  'non_featured':Post.objects.filter(featured=False)
})

但我真的不喜欢这种方法,有没有“基于模板”的解决方案?

谢谢!

【问题讨论】:

    标签: python django templates for-loop


    【解决方案1】:

    Regroupfeatured 字段上。

    【讨论】:

    • 就是这样!真的很简单!不知道我怎么错过了。谢谢伊格纳西奥。
    • 因为我需要再等 3 分钟,然后去吃晚饭。我没有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 2021-01-30
    • 2021-01-10
    • 2019-09-03
    • 1970-01-01
    相关资源
    最近更新 更多