user13128719
user13128719

Reputation:

Django count() function

(noob question I know) Hi everybody, I keep having a problem with the count() function. In my website I added some items to the database, then I'd like to show on the hompage the number of items, but the count doesn't show up. I really can't figure out what I'm doing wrong.

this is the code: View.py:

class homeView(TemplateView):
    template_name = 'search/home.html'

    def conto(self):
        album = Info.objects.all().count()
        return album

Html file:

<h3 style="text-align:center;"> ALBUM TOTALI: {{album}} </h3>

Upvotes: 1

Views: 742

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

You can render this with:

<h3 style="text-align:center;"> ALBUM TOTALI: {{ view.conto }} </h3>

This works because the ContextMixin [Django-doc] passes the view to the template under the name view, and you can thus access the method with view.conto.

Upvotes: 1

drec4s
drec4s

Reputation: 8077

You need to override the get_context_data method of the TemplateView you are inheriting from:

class homeView(TemplateView):
    template_name = 'search/home.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['album'] = Info.objects.all().count()
        return context

Upvotes: 5

Related Questions