How to count object and include the result in template

159 Views Asked by At

I need to push number of items to template to have adaptive website in function of number of items.

In the models.py I add get_context

models.py

    from __future__ import absolute_import, unicode_literals

from django.db import models

from wagtail.wagtailcore.models import Page
from wagtail.wagtailimages.models import Image
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailimages.edit_handlers import ImageChooserPanel


class HomePage(Page):
    auteur = models.CharField(max_length=250,default='Luc Simard')
    subpage_types = ['LivreDesc']
    content_panels = Page.content_panels + [
        FieldPanel('auteur', classname="full"),
    ]


class LivreDesc(Page):
    note = models.CharField(max_length=25,null=True,blank=True,)
    resume = RichTextField(blank=True, verbose_name="Résumé")
    couverture = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL, verbose_name="Couverture du livre")
    parent_page_type = ['HomePage']
    subpage_types = []

    content_panels = Page.content_panels + [
        FieldPanel('note'),
        FieldPanel('resume', classname="full"),     
        ImageChooserPanel('couverture'),     
    ]

    def get_context(self, request):
        context = super(LivreDesc, self).get_context(request)
        context['nb_livres'] =  LivreDesc.objects.all().count()
        return context

In template of HomePage I add this but I don't see anything

{{ nb_livres }}
1

There are 1 best solutions below

0
On BEST ANSWER

If you want the variable to be available in the homepage template, you need to overwrite the get_context method on the HomePage model not LivreDesc.