如何计算对象并将结果包含在模板中

时间:2017-09-07 01:27:23

标签: django wagtail

我需要将项目数量推送到模板,以便在项目数量的作用下具有自适应网站。

在models.py中,我添加了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

在HomePage的模板中我添加了这个,但是我没有看到任何内容

{{ nb_livres }}

1 个答案:

答案 0 :(得分:1)

如果您希望变量在主页模板中可用,则需要覆盖get_context模型上的HomePage方法,而不是LivreDesc