5

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

3 Answers 3

10

You can use this template filter:

{{ places|length }} 

Documentation link length

Don’t overuse count() and exists()

Optimization

Sign up to request clarification or add additional context in comments.

1 Comment

Not problem, but i think you should use this solution, because this for no additional queries.
6

You can't get the count of objects in django's template without writing a custom tag.

Even if you could however it would be 10, since you especially said places to only include 10 objects.

You should instead pass places_count via the context to the template:

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

And then in the template:

<div class="container">
    <h2>Places <span class="badge">{{ places_count }}</span></h2>
</div>

Comments

0

On the htmlpage;

{% if products %}
    Number of products: {{ products|length }}
{% else %}
    No products.
{% endif %}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.