Python wagtail.core.blocks.StructBlock() Examples

The following are 30 code examples of wagtail.core.blocks.StructBlock(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module wagtail.core.blocks , or try the search function .
Example #1
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_render_with_template(self):

        class SectionStructValue(blocks.StructValue):
            def title_with_suffix(self):
                title = self.get('title')
                if title:
                    return 'SUFFIX %s' % title
                return 'EMPTY TITLE'

        class SectionBlock(blocks.StructBlock):
            title = blocks.CharBlock(required=False)

            class Meta:
                value_class = SectionStructValue

        block = SectionBlock(template='tests/blocks/struct_block_custom_value.html')
        struct_value = block.to_python({'title': 'hello'})
        html = block.render(struct_value)
        self.assertEqual(html, '<div>SUFFIX hello</div>\n')

        struct_value = block.to_python({})
        html = block.render(struct_value)
        self.assertEqual(html, '<div>EMPTY TITLE</div>\n') 
Example #2
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_system_checks_recurse_into_lists(self):
        failing_block = blocks.RichTextBlock()
        block = blocks.StreamBlock([
            ('paragraph_list', blocks.ListBlock(
                blocks.StructBlock([
                    ('heading', blocks.CharBlock()),
                    ('rich text', failing_block),
                ])
            ))
        ])

        errors = block.check()
        self.assertEqual(len(errors), 1)
        self.assertEqual(errors[0].id, 'wagtailcore.E001')
        self.assertEqual(errors[0].hint, "Block names cannot contain spaces")
        self.assertEqual(errors[0].obj, failing_block) 
Example #3
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_default_is_returned_as_structvalue(self):
        """When returning the default value of a StructBlock (e.g. because it's
        a child of another StructBlock, and the outer value is missing that key)
        we should receive it as a StructValue, not just a plain dict"""
        class PersonBlock(blocks.StructBlock):
            first_name = blocks.CharBlock()
            surname = blocks.CharBlock()

        class EventBlock(blocks.StructBlock):
            title = blocks.CharBlock()
            guest_speaker = PersonBlock(default={'first_name': 'Ed', 'surname': 'Balls'})

        event_block = EventBlock()

        event = event_block.to_python({'title': 'Birthday party'})

        self.assertEqual(event['guest_speaker']['first_name'], 'Ed')
        self.assertTrue(isinstance(event['guest_speaker'], blocks.StructValue)) 
Example #4
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_system_checks_recurse_into_streams(self):
        failing_block = blocks.RichTextBlock()
        block = blocks.StreamBlock([
            ('carousel', blocks.StreamBlock([
                ('text', blocks.StructBlock([
                    ('heading', blocks.CharBlock()),
                    ('rich text', failing_block),
                ]))
            ]))
        ])

        errors = block.check()
        self.assertEqual(len(errors), 1)
        self.assertEqual(errors[0].id, 'wagtailcore.E001')
        self.assertEqual(errors[0].hint, "Block names cannot contain spaces")
        self.assertEqual(errors[0].obj, failing_block) 
Example #5
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_system_checks_recurse_into_structs(self):
        failing_block_1 = blocks.RichTextBlock()
        failing_block_2 = blocks.RichTextBlock()
        block = blocks.StreamBlock([
            ('two_column', blocks.StructBlock([
                ('left', blocks.StructBlock([
                    ('heading', blocks.CharBlock()),
                    ('rich text', failing_block_1),
                ])),
                ('right', blocks.StructBlock([
                    ('heading', blocks.CharBlock()),
                    ('rich text', failing_block_2),
                ]))
            ]))
        ])

        errors = block.check()
        self.assertEqual(len(errors), 2)
        self.assertEqual(errors[0].id, 'wagtailcore.E001')
        self.assertEqual(errors[0].hint, "Block names cannot contain spaces")
        self.assertEqual(errors[0].obj, failing_block_1)
        self.assertEqual(errors[1].id, 'wagtailcore.E001')
        self.assertEqual(errors[1].hint, "Block names cannot contain spaces")
        self.assertEqual(errors[1].obj, failing_block_2) 
Example #6
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_initialisation_from_subclass(self):

        class LinkStructValue(blocks.StructValue):
            def url(self):
                return self.get('page') or self.get('link')

        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock()
            page = blocks.PageChooserBlock(required=False)
            link = blocks.URLBlock(required=False)

            class Meta:
                value_class = LinkStructValue

        block = LinkBlock()

        self.assertEqual(list(block.child_blocks.keys()), ['title', 'page', 'link'])

        block_value = block.to_python({'title': 'Website', 'link': 'https://website.com'})
        self.assertIsInstance(block_value, LinkStructValue)

        default_value = block.get_default()
        self.assertIsInstance(default_value, LinkStructValue) 
Example #7
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_constructor_default(self):
        """Test that we can specify a default value in the constructor of a StreamBlock"""

        class ArticleBlock(blocks.StreamBlock):
            heading = blocks.CharBlock()
            paragraph = blocks.CharBlock()

            class Meta:
                default = [('heading', 'A default heading')]

        # to access the default value, we retrieve it through a StructBlock
        # from a struct value that's missing that key
        class ArticleContainerBlock(blocks.StructBlock):
            author = blocks.CharBlock()
            article = ArticleBlock(default=[('heading', 'A different default heading')])

        block = ArticleContainerBlock()
        struct_value = block.to_python({'author': 'Bob'})
        stream_value = struct_value['article']

        self.assertTrue(isinstance(stream_value, blocks.StreamValue))
        self.assertEqual(len(stream_value), 1)
        self.assertEqual(stream_value[0].block_type, 'heading')
        self.assertEqual(stream_value[0].value, 'A different default heading') 
Example #8
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_render_form_with_help_text(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock()
            link = blocks.URLBlock()

            class Meta:
                help_text = "Self-promotion is encouraged"

        block = LinkBlock()
        html = block.render_form(block.to_python({
            'title': "Wagtail site",
            'link': 'http://www.wagtail.io',
        }), prefix='mylink')

        self.assertInHTML('<div class="help"><span class="icon-help-inverse" aria-hidden="true"></span> Self-promotion is encouraged</div>', html)

        # check it can be overridden in the block constructor
        block = LinkBlock(help_text="Self-promotion is discouraged")
        html = block.render_form(block.to_python({
            'title': "Wagtail site",
            'link': 'http://www.wagtail.io',
        }), prefix='mylink')

        self.assertInHTML('<div class="help"><span class="icon-help-inverse" aria-hidden="true"></span> Self-promotion is discouraged</div>', html) 
Example #9
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_value_property(self):

        class SectionStructValue(blocks.StructValue):
            @property
            def foo(self):
                return 'bar %s' % self.get('title', '')

        class SectionBlock(blocks.StructBlock):
            title = blocks.CharBlock()
            body = blocks.RichTextBlock()

            class Meta:
                value_class = SectionStructValue

        block = SectionBlock()
        struct_value = block.to_python({'title': 'hello', 'body': '<b>world</b>'})
        value = struct_value.foo
        self.assertEqual(value, 'bar hello') 
Example #10
Source File: fields.py    From wagtailstreamforms with MIT License 6 votes vote down vote up
def get_form_block(self):
        """The StreamField StructBlock.

        Override this to provide additional fields in the StreamField.

        :return: The ``wagtail.core.blocks.StructBlock`` to be used in the StreamField
        """
        return blocks.StructBlock(
            [
                ("label", blocks.CharBlock()),
                ("help_text", blocks.CharBlock(required=False)),
                ("required", blocks.BooleanBlock(required=False)),
                ("default_value", blocks.CharBlock(required=False)),
            ],
            icon=self.icon,
            label=self.label,
        ) 
Example #11
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_custom_render_form_template_jinja(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock(required=False)
            link = blocks.URLBlock(required=False)

            class Meta:
                form_template = 'tests/jinja2/struct_block_form_template.html'

        block = LinkBlock()
        html = block.render_form(block.to_python({
            'title': "Wagtail site",
            'link': 'http://www.wagtail.io',
        }), prefix='mylink')

        self.assertIn('<div>Hello</div>', html)
        self.assertHTMLEqual('<div>Hello</div>', html)
        self.assertTrue(isinstance(html, SafeText)) 
Example #12
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_custom_render_form_template(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock(required=False)
            link = blocks.URLBlock(required=False)

            class Meta:
                form_template = 'tests/block_forms/struct_block_form_template.html'

        block = LinkBlock()
        html = block.render_form(block.to_python({
            'title': "Wagtail site",
            'link': 'http://www.wagtail.io',
        }), prefix='mylink')

        self.assertIn('<div>Hello</div>', html)
        self.assertHTMLEqual('<div>Hello</div>', html)
        self.assertTrue(isinstance(html, SafeText)) 
Example #13
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock()
            link = blocks.URLBlock()

        block = blocks.ListBlock(LinkBlock())
        return block.render([
            {
                'title': "Wagtail",
                'link': 'http://www.wagtail.io',
            },
            {
                'title': "Django",
                'link': 'http://www.djangoproject.com',
            },
        ]) 
Example #14
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_render_unknown_field(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock()
            link = blocks.URLBlock()

        block = LinkBlock()
        html = block.render(block.to_python({
            'title': "Wagtail site",
            'link': 'http://www.wagtail.io',
            'image': 10,
        }))

        self.assertIn('<dt>title</dt>', html)
        self.assertIn('<dd>Wagtail site</dd>', html)
        self.assertIn('<dt>link</dt>', html)
        self.assertIn('<dd>http://www.wagtail.io</dd>', html)

        # Don't render the extra item
        self.assertNotIn('<dt>image</dt>', html) 
Example #15
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render_form(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock()
            link = blocks.URLBlock()

        block = blocks.ListBlock(LinkBlock)

        html = block.render_form([
            {
                'title': "Wagtail",
                'link': 'http://www.wagtail.io',
            },
            {
                'title': "Django",
                'link': 'http://www.djangoproject.com',
            },
        ], prefix='links')

        return html 
Example #16
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_render(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock()
            link = blocks.URLBlock()

        block = LinkBlock()
        html = block.render(block.to_python({
            'title': "Wagtail site",
            'link': 'http://www.wagtail.io',
        }))
        expected_html = '\n'.join([
            '<dl>',
            '<dt>title</dt>',
            '<dd>Wagtail site</dd>',
            '<dt>link</dt>',
            '<dd>http://www.wagtail.io</dd>',
            '</dl>',
        ])

        self.assertHTMLEqual(html, expected_html) 
Example #17
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_html_declarations(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock()
            link = blocks.URLBlock()

        block = blocks.ListBlock(LinkBlock)
        html = block.html_declarations()

        self.assertTagInTemplateScript(
            '<input id="__PREFIX__-value-title" name="__PREFIX__-value-title" placeholder="Title" type="text" />',
            html
        )
        self.assertTagInTemplateScript(
            '<input id="__PREFIX__-value-link" name="__PREFIX__-value-link" placeholder="Link" type="url" />',
            html
        ) 
Example #18
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_searchable_content(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock()
            link = blocks.URLBlock()

        block = blocks.ListBlock(LinkBlock())
        content = block.get_searchable_content([
            {
                'title': "Wagtail",
                'link': 'http://www.wagtail.io',
            },
            {
                'title': "Django",
                'link': 'http://www.djangoproject.com',
            },
        ])

        self.assertEqual(content, ["Wagtail", "Django"]) 
Example #19
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_default_default(self):
        """
        if no explicit 'default' is set on the ListBlock, it should fall back on
        a single instance of the child block in its default state.
        """
        class ShoppingListBlock(blocks.StructBlock):
            shop = blocks.CharBlock()
            items = blocks.ListBlock(blocks.CharBlock(default='chocolate'))

        block = ShoppingListBlock()
        # the value here does not specify an 'items' field, so this should revert to the ListBlock's default
        form_html = block.render_form(block.to_python({'shop': 'Tesco'}), prefix='shoppinglist')

        self.assertIn(
            '<input type="hidden" name="shoppinglist-items-count" id="shoppinglist-items-count" value="1">',
            form_html
        )
        self.assertIn('value="chocolate"', form_html) 
Example #20
Source File: test_embeds.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_render_within_structblock(self, get_embed):
        """
        When rendering the value of an EmbedBlock directly in a template
        (as happens when accessing it as a child of a StructBlock), the
        proper embed output should be rendered, not the URL.
        """
        get_embed.return_value = Embed(html='<h1>Hello world!</h1>')

        block = blocks.StructBlock([
            ('title', blocks.CharBlock()),
            ('embed', EmbedBlock()),
        ])

        block_val = block.to_python({'title': 'A test', 'embed': 'http://www.example.com/foo'})

        temp = template.Template('embed: {{ self.embed }}')
        context = template.Context({'self': block_val})
        result = temp.render(context)

        self.assertIn('<h1>Hello world!</h1>', result)

        # Check that get_embed was called correctly
        get_embed.assert_any_call('http://www.example.com/foo') 
Example #21
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_render_with_classname_via_kwarg(self):
        """form_classname from kwargs to be used as an additional class when rendering list block"""

        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock()
            link = blocks.URLBlock()

        block = blocks.ListBlock(LinkBlock, form_classname='special-list-class')

        html = block.render_form([
            {
                'title': "Wagtail",
                'link': 'http://www.wagtail.io',
            },
            {
                'title': "Django",
                'link': 'http://www.djangoproject.com',
            },
        ], prefix='links')

        # including leading space to ensure class name gets added correctly
        self.assertEqual(html.count(' special-list-class'), 1) 
Example #22
Source File: wagtailstreamforms_fields.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def get_form_block(self):
        return blocks.StructBlock([
            ('label', blocks.CharBlock()),
            ('help_text', blocks.CharBlock(required=False)),
            ('required', blocks.BooleanBlock(required=False)),
            ('regex', blocks.ChoiceBlock(choices=self.get_regex_choices())),
            ('error_message', blocks.CharBlock()),
            ('default_value', blocks.CharBlock(required=False)),
        ], icon=self.icon, label=self.label) 
Example #23
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_render_with_classname_via_class_meta(self):
        """form_classname from meta to be used as an additional class when rendering list block"""

        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock()
            link = blocks.URLBlock()

        class CustomListBlock(blocks.ListBlock):

            class Meta:
                form_classname = 'custom-list-class'

        block = CustomListBlock(LinkBlock)

        html = block.render_form([
            {
                'title': "Wagtail",
                'link': 'http://www.wagtail.io',
            },
            {
                'title': "Django",
                'link': 'http://www.djangoproject.com',
            },
        ], prefix='links')

        # including leading space to ensure class name gets added correctly
        self.assertEqual(html.count(' custom-list-class'), 1) 
Example #24
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_get_prep_value_nested_streamblocks(self, stream_data, is_lazy):
        class TwoColumnBlock(blocks.StructBlock):
            left = blocks.StreamBlock([('text', blocks.CharBlock())])
            right = blocks.StreamBlock([('text', blocks.CharBlock())])

        block = TwoColumnBlock()

        value = {
            k: blocks.StreamValue(block.child_blocks[k], v, is_lazy=is_lazy)
            for k, v in stream_data.items()
        }
        jsonish_value = block.get_prep_value(value)

        self.assertEqual(len(jsonish_value), 2)
        self.assertEqual(
            jsonish_value['left'],
            [{'type': 'text', 'value': 'some text', 'id': '0000'}]
        )

        self.assertEqual(len(jsonish_value['right']), 1)
        right_block = jsonish_value['right'][0]
        self.assertEqual(right_block['type'], 'text')
        self.assertEqual(right_block['value'], 'some other text')
        # get_prep_value should assign a new (random and non-empty)
        # ID to this block, as it didn't have one already.
        self.assertTrue(right_block['id']) 
Example #25
Source File: wagtailstreamforms_fields.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def get_form_block(self):
        return blocks.StructBlock([
            ('label', blocks.CharBlock()),
            ('help_text', blocks.CharBlock(required=False)),
        ], icon=self.icon, label=self.label) 
Example #26
Source File: streamfield.py    From wagtail-graphql with MIT License 5 votes vote down vote up
def _is_compound_block(block):
    return isinstance(block, StructBlock) 
Example #27
Source File: wagtailstreamforms_fields.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def get_form_block(self):
        return blocks.StructBlock([
            ('label', blocks.CharBlock()),
            ('help_text', blocks.CharBlock(required=False)),
            ('required', blocks.BooleanBlock(required=False)),
        ], icon=self.icon, label=self.label) 
Example #28
Source File: wagtailstreamforms_fields.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def get_form_block(self):
        return blocks.StructBlock(
            [
                ("label", blocks.CharBlock()),
                ("help_text", blocks.CharBlock(required=False)),
                ("required", blocks.BooleanBlock(required=False)),
                ("empty_label", blocks.CharBlock(required=False)),
                ("choices", blocks.ListBlock(blocks.CharBlock(label="Option"))),
            ],
            icon=self.icon,
            label=self.label,
        ) 
Example #29
Source File: wagtailstreamforms_fields.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def get_form_block(self):
        return blocks.StructBlock(
            [
                ("label", blocks.CharBlock()),
                ("help_text", blocks.CharBlock(required=False)),
                ("required", blocks.BooleanBlock(required=False)),
                ("choices", blocks.ListBlock(blocks.CharBlock(label="Option"))),
            ],
            icon=self.icon,
            label=self.label,
        ) 
Example #30
Source File: wagtailstreamforms_fields.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def get_form_block(self):
        return blocks.StructBlock(
            [
                ("label", blocks.CharBlock()),
                ("help_text", blocks.CharBlock(required=False)),
                ("required", blocks.BooleanBlock(required=False)),
                ("choices", blocks.ListBlock(blocks.CharBlock(label="Option"))),
            ],
            icon=self.icon,
            label=self.label,
        )