Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - print length of dict in template

Tags:

python

django

I believe this one will be very basic. I am trying to show the number of values in a dictionary on a template. Here is my method for the template route:

# url: localhost/books/home/
def books_home(request):
    if request.method == "GET":
        first_name = User.objects.get(id=request.session['uid']).first_name
        last_name = User.objects.get(id=request.session['uid']).last_name
        email = User.objects.get(id=request.session['uid']).email
        user_id = User.objects.get(id=request.session['uid']).id
        reviews = Review.objects.filter(created_by=request.session['uid']).order_by("-created_at")[:3]
        context = {
            'first_name' : first_name, 
            'email' : email,
            'last_name' : last_name,
            'reviews' : reviews,
            }
        return render(request, 'html_files/home.html', context=context)

Then the pertinent code in the template:

<div class="container">
        <div class="card">
            <h3>Information for {{ first_name }} {{ last_name }}</h3>
            <p>email: {{ email }} </p>
            <p>Number of reviews: {{ len(reviews) }}</p>
        </div>
        <div class="card">
            <h3>Your recent reviews:</h3>
            {% for review in reviews %}
                <p>Review for: <a href="/books/book/{{ review.book.id }}/">{{ review.book.title}}</a> by {{ review.book.author.first_name }} {{ review.book.author.last_name }} <br><br>
                Your review: {{ review.comments }} <br><br>
                Your rating: {{ review.rating }} out of 5</p><br><br><br>
            {% endfor %}
        </div>

I thought that {{ len(reviews }} would do it, since as you can see below, "reviews" has been successfully passed to the context dict. But I am getting a "could not parse remainder" error. Your help is appreciated.

like image 668
garreth Avatar asked Sep 06 '25 13:09

garreth


1 Answers

The tutorial and documentation are explicit that Django template syntax doesn't support calling functions with arguments.

In this case, you can use the length filter:

{{ reviews|length }}

Alternatively, since reviews is a queryset (not a dict), you could call its count method:

{{ reviews.count }}
like image 54
Daniel Roseman Avatar answered Sep 08 '25 10:09

Daniel Roseman