9

I don't found proper way to update Wagtail CMS Page context.

For instance i have my homepage model:

class HomePage(Page):
    about = RichTextField(blank=True)
    date = models.DateField(auto_now=True)

    content_panels = Page.content_panels + [
        FieldPanel('about', classname="full")
    ]

    class Meta:
        verbose_name = "Homepage"

And I also want some third part information to be included on that page. In my case its forum. It will be great to write some ViewMixin, like:

class ForumMixin(object):
    pass
    # add latest forums to context

I can do it by writing my Django CBV, but i really want to know Wagtail Native Way. Thanks!

yanik
  • 798
  • 11
  • 33

1 Answers1

24

You can do this by overriding the get_context method on your page model:

class HomePage(Page):
    def get_context(self, request):
        context = super(HomePage, self).get_context(request)
        context['forums'] = Forum.objects.all()
        return context

This makes the variable forums available on your template.

gasman
  • 23,691
  • 1
  • 38
  • 56
  • 2
    Thanks, but don't you think it's a bit stupid - write views login into models? – yanik Sep 18 '15 at 08:35
  • 5
    Not really :-) In Wagtail, pages are ORM objects that know how to render themselves, so there will inevitably be some crossover between view logic and models. Sure, it's not traditional MVC, but I believe it's a good fit for what a content management system is meant to do. – gasman Sep 18 '15 at 15:57
  • 1
    Just to tease at this because it makes me nervous... even if putting this functionality in the model _works_, wouldn't it make _more sense_ to put it in a view instead? Otherwise, might this work in a template tag, like in http://docs.wagtail.io/en/v1.5.2/topics/snippets.html ? – allanberry Jul 06 '16 at 04:06
  • The old docs has a stub for this, never expanded: http://docs.wagtail.io/en/v0.8.7/core_components/pages/model_recipes.html#custom-page-contexts-by-overriding-get-context – allanberry Jul 06 '16 at 17:31
  • 8
    This isn't really the place for me to defend Wagtail's design decisions. The question was, what's the standard Wagtail convention for passing extra context to the template, and that's exactly what I've given you here. You might think that it's ugly, and that's absolutely fine - you're very welcome to look for an alternative that suits your aesthetic sensibilities better :-) – gasman Jul 06 '16 at 20:53