1

(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>
2
  • 3
    If you want to display custom variables in the template, I believe you have to supply a get_context_data() method. Commented May 21, 2020 at 16:26
  • I did what @johnGordon said, and obiovsly it worked aahah sorry I'm really new to Django Commented May 21, 2020 at 16:36

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Ah that's great! I'll keep it in mind because could be very useful for other things. Thanks a lot!

Your Answer

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