Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show objects count in Django template

Tags:

django

I have a program that post some places and shows them in a HTML template, but I also want to show the users many of these places I have and I'm wondering how I can reach this.

I have in my models.py:

class Places(models.Model):
     name=models.CharField(max_length=100)
     text=models.TextField()
     website=models.URLField()
     published_date = models.DateTimeField(
            blank=True, null=True)

def __str__(self):
    return self.name

def publish(self):
        self.published_date = timezone.now()
        self.save()

in views.py:

def places(request):
     places=Places.objects.order_by('-published_date')[:10]
     return render(request, 'templates/places.html', {'places':places})

and the html template:

<div class="container">
<h2>Places<span class="badge"> HERE'S WHERE I WANT THE NUMBER OF PLACES</h2>
</div>

I hope you can help me out. Thanks for the answers

like image 516
INME Avatar asked Sep 19 '15 19:09

INME


People also ask

What does {% mean in Django?

{% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does {% include %} do in Django?

The include tag allows you include a template inside the current template. This is useful when you have a block of content that are the same for many pages.

What is {% block content %} in Django?

Introducing {% block %} The block tag is used to define a block that can be overridden by child templates. In other words, when you define a block in the base template, you're saying that this area will be populated with content from a different, child template file.


1 Answers

You can use this template filter:

{{ places|length }} 

Documentation link length

Don’t overuse count() and exists()

Optimization

like image 95
Paulo Pessoa Avatar answered Sep 25 '22 07:09

Paulo Pessoa