【问题标题】:How do I make a counter in Django that is displayed in the template?如何在 Django 中创建一个显示在模板中的计数器?
【发布时间】:2021-04-22 14:39:45
【问题描述】:

Models.py

class Coche(models.Model):  
    matricula = models.CharField(max_length=7,primary_key=True)

Views.py

class Index(ListView):
    model = Coche
    total_coches = Coche.objects.filter(reserved=False, sold=False)  

模板

<span class="text-primary">{{ total_coches.count }}</span> <span>coches disponibles</span></span>


### 它不显示我的应用程序拥有的汽车数量。有谁知道故障是什么? ###

【问题讨论】:

  • views.py 文件有 template_name = index.html。
  • 以total_coches 的名义,我猜你想要该行中的coches 数。那么为什么不直接在视图中的同一行中获取计数呢?

标签: python django templates view count


【解决方案1】:

要将上下文传递给 Django 通用视图中的模板,您需要使用 get_context_data mixin。

class Index(ListView):
    model = Coche
    def get_context_data(self, *args, **kwargs):
        context = super(Index, self).get_context_data(*args, **kwargs)
        context['total_coches'] = Coche.objects.filter(reserved=False, sold=False)
        return context

如果您只需要计数器而不是整个查询集,最好在 cmets 中遵循 Kurosh 的建议并在您的视图中定义它。

class Index(ListView):
    model = Coche
    def get_context_data(self, *args, **kwargs):
        context = super(Index, self).get_context_data(*args, **kwargs)
        context['total_coches'] = Coche.objects.filter(reserved=False, sold=False).count()
        return context

然后在您的模板中使用{{total_coches}}

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2011-07-01
  • 2021-10-01
  • 1970-01-01
  • 2021-10-14
  • 2017-11-13
  • 2011-03-12
  • 1970-01-01
  • 2016-05-06
  • 1970-01-01
相关资源
最近更新 更多