Wagtail Views: extra context
Asked Answered
M

1

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!

Muskellunge answered 17/9, 2015 at 9:25 Comment(0)
S
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.

Sedative answered 17/9, 2015 at 23:45 Comment(5)
Thanks, but don't you think it's a bit stupid - write views login into models?Muskellunge
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.Sedative
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 docs.wagtail.io/en/v1.5.2/topics/snippets.html ?Sporogony
The old docs has a stub for this, never expanded: docs.wagtail.io/en/v0.8.7/core_components/pages/…Sporogony
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 :-)Sedative

© 2022 - 2024 — McMap. All rights reserved.