How to access attributes of the chosen page via PageChooserBlock() in StreamField template?

1,037 views
Skip to first unread message

kdli...@gmail.com

unread,
Jun 5, 2015, 4:44:19 AM6/5/15
to wag...@googlegroups.com
Say I have the following wagtail code:

class HomePage(Page):
    body
= StreamField([
       
('heading', blocks.CharBlock(classname="full")),
       
('carousel', ListBlock(
           
StructBlock([
               
('image', ImageChooserBlock()),
               
('page', PageChooserBlock()),
               
('quotation', TextBlock()),
           
]), icon='cogs', template='shop/blocks/carousel.html')),
   
])

And in the editing interface I chose a page via `PageChooserBlock()`, Let's say the chosen page is defined as below:

class ItemPage(Page):
    intro
= models.CharField(max_length=255)
    body
= RichTextField()



So how to access this page's attributes in the `shop/blocks/carousel.html` template?

what I want is like this:

{% for item in self %}
 
<a href="{{ item.page.url }}">
     
{% image item.image width-400 %}
     
{{ item.quotation }}
     
{{ item.page.intro }}
     
{{ item.page.body }}
 
</a>
{% endfor %}

`{{ item.page.url }}`, {{ item.quotation }} and {{ item.image }} work, but `{{ item.page.intro }}` and `{{ item.page.body }}` don't work.

I must be using StreamField in the wrong way, I think.

Matthew Westcott

unread,
Jun 5, 2015, 5:00:13 AM6/5/15
to wag...@googlegroups.com
This is failing because the PageChooserBlock only returns a plain Page instance, which doesn't include the additional intro/body fields from ItemPage. You can convert the Page instance to an instance of ItemPage (at the cost of an extra database query) by accessing {{ item.page.specific }}.

(It's on our todo list to support something like PageChooserBlock(page_type=ItemPage), which would return the ItemPage, and also ensure that editors can only choose ItemPages in the page chooser.)

Cheers,
- Matt

kdli...@gmail.com

unread,
Jun 5, 2015, 5:08:35 AM6/5/15
to wag...@googlegroups.com
Thank you so much Matt. I'm very looking forward to the PageChooserBlock(page_type=ItemPage) feature! Thank you again.


在 2015年6月5日星期五 UTC+8下午5:00:13,Matthew Westcott写道:
Reply all
Reply to author
Forward
0 new messages