简体   繁体   中英

How do I make a counter in Django that is displayed in the template?

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)  

Template

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


### It does not show the number of cars my application has. Does anyone know what the fault is? ###

To pass context to the template in Django generic views you need to use the 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

If you just need the counter instead of the whole queryset, it would be better to follow Kurosh's suggestion in the comments and define it in your view.

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

Then in your template you just use {{total_coches}} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM