I have created a Wagtail settings page that allows me to select 1-5 pages which I'd like to display in my site footer as 'Most popular pages'. I've done this using an Orderable and PageChooserPanel, see below:
@register_setting
class MostPopularPosts(BaseSetting, ClusterableModel):
display_most_popular_posts_in_sidebar = models.BooleanField("Display most popular posts in sidebar", default=True, help_text='Untick to hide the most popular posts widget')
panels = [
FieldPanel('display_most_popular_posts_in_sidebar'),
InlinePanel('popular_pages', max_num=5, min_num=1, label="Most popular pages"),
]
class MostPopularPostPages(Orderable):
settings_page = ParentalKey(MostPopularPosts, related_name="popular_pages")
popular_page = models.ForeignKey(
'wagtailcore.Page',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name=' ',
verbose_name="Page Link"
)
panels = [
PageChooserPanel('popular_page')
]
The above works fine, but I'm struggling to get the content of the individual pages selected to appear in my templates.
{% for popular_page in settings.home.MostPopularPosts.popular_pages.all %}
<li>
{{ popular_page.title }}
</li>
{% endfor %}
The above loop iterates the expected number of times, but {{ popular_page.title }} doesn't output the page titles. I've tried {{ popular_page.specific.title }} but this also doesn't work.
If someone could explain how I should be structuring my template tags to access the individual pages data within my for loop here I'd be eternally grateful.
CodePudding user response:
Your loop will return instances of the MostPopularPostPages
model, which are not page objects in their own right. To get a page object (and thus access the title
field), you'll need to follow the ForeignKey that points to wagtailcore.Page
, which is the popular_page
relation. Renaming your existing popular_page
variable to item
to avoid confusion, we get:
{% for item in settings.home.MostPopularPosts.popular_pages.all %}
<li>
{{ item.popular_page.title }}
</li>
{% endfor %}