Python wagtail.core.blocks.StreamBlock() Examples

The following are 30 code examples of wagtail.core.blocks.StreamBlock(). 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_jinja2.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_block_render_result_is_safe(self):
        """
        Ensure that any results of template rendering in block.render are marked safe
        so that they don't get double-escaped when inserted into a parent template (#2541)
        """
        stream_block = blocks.StreamBlock([
            ('paragraph', blocks.CharBlock(template='tests/jinja2/paragraph.html'))
        ])

        stream_value = stream_block.to_python([
            {'type': 'paragraph', 'value': 'hello world'},
        ])

        result = render_to_string('tests/jinja2/stream.html', {
            'value': stream_value,
        })

        self.assertIn('<p>hello world</p>', result) 
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_include_block_tag_with_streamvalue(self):
        """
        The include_block tag should be able to render a StreamValue's template
        while keeping the parent template's context
        """
        block = blocks.StreamBlock([
            ('heading', blocks.CharBlock(template='tests/blocks/heading_block.html')),
            ('paragraph', blocks.CharBlock()),
        ], template='tests/blocks/stream_with_language.html')

        stream_value = block.to_python([
            {'type': 'heading', 'value': 'Bonjour'}
        ])

        result = render_to_string('tests/blocks/include_block_test.html', {
            'test_block': stream_value,
            'language': 'fr',
        })

        self.assertIn('<div class="heading" lang="fr"><h1 lang="fr">Bonjour</h1></div>', result) 
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_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 #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_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 #6
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_class_meta(self):
        """form_classname from meta to be used as an additional class when rendering stream block"""

        class ProfileBlock(blocks.StreamBlock):
            username = blocks.CharBlock()

            class Meta:
                form_classname = 'profile-block-large'

        block = ProfileBlock()
        value = block.to_python([
            {
                'type': 'username',
                'value': "renegadeM@ster",
                'id': '789',
            }
        ])

        html = block.render_form(value, prefix='profiles')

        # including leading space to ensure class name gets added correctly
        self.assertEqual(html.count(' profile-block-large'), 1) 
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_render_with_classname_via_kwarg(self):
        """form_classname from kwargs to be used as an additional class when rendering stream block"""

        block = blocks.StreamBlock([
            (b'heading', blocks.CharBlock()),
            (b'paragraph', blocks.CharBlock()),
        ], form_classname='rocket-section')

        value = block.to_python([
            {
                'type': 'heading',
                'value': "Falcon Heavy",
                'id': '2',
            },
            {
                'type': 'paragraph',
                'value': "Ultra heavy launch capability",
                'id': '3',
            }
        ])

        html = block.render_form(value)

        # including leading space to ensure class name gets added correctly
        self.assertEqual(html.count(' rocket-section'), 1) 
Example #8
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_get_prep_value(self, stream_data, is_lazy):
        class ArticleBlock(blocks.StreamBlock):
            heading = blocks.CharBlock()
            paragraph = blocks.CharBlock()

        block = ArticleBlock()

        value = blocks.StreamValue(block, stream_data, is_lazy=is_lazy)
        jsonish_value = block.get_prep_value(value)

        self.assertEqual(len(jsonish_value), 2)
        self.assertEqual(jsonish_value[0], {'type': 'heading', 'value': 'this is my heading', 'id': '0000'})
        self.assertEqual(jsonish_value[1]['type'], 'paragraph')
        self.assertEqual(jsonish_value[1]['value'], '<p>this is a paragraph</p>')
        # get_prep_value should assign a new (random and non-empty)
        # ID to this block, as it didn't have one already.
        self.assertTrue(jsonish_value[1]['id'])

        # Calling get_prep_value again should preserve existing IDs, including the one
        # just assigned to block 1
        jsonish_value_again = block.get_prep_value(value)
        self.assertEqual(jsonish_value[0]['id'], jsonish_value_again[0]['id'])
        self.assertEqual(jsonish_value[1]['id'], jsonish_value_again[1]['id']) 
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_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 #10
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ordering_in_form_submission_is_numeric(self):
        class ArticleBlock(blocks.StreamBlock):
            heading = blocks.CharBlock()
            paragraph = blocks.CharBlock()

        block = ArticleBlock()

        # check that items are ordered by 'order' numerically, not alphabetically
        post_data = {'article-count': '12'}
        for i in range(0, 12):
            post_data.update({
                'article-%d-deleted' % i: '',
                'article-%d-order' % i: str(i),
                'article-%d-type' % i: 'heading',
                'article-%d-value' % i: "heading %d" % i
            })

        block_value = block.value_from_datadict(post_data, {}, 'article')
        self.assertEqual(block_value[2].value, "heading 2") 
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_ordering_in_form_submission_uses_order_field(self):
        class ArticleBlock(blocks.StreamBlock):
            heading = blocks.CharBlock()
            paragraph = blocks.CharBlock()

        block = ArticleBlock()

        # check that items are ordered by the 'order' field, not the order they appear in the form
        post_data = {'article-count': '3'}
        for i in range(0, 3):
            post_data.update({
                'article-%d-deleted' % i: '',
                'article-%d-order' % i: str(2 - i),
                'article-%d-type' % i: 'heading',
                'article-%d-value' % i: "heading %d" % i,
                'article-%d-id' % i: "000%d" % i,
            })

        block_value = block.value_from_datadict(post_data, {}, 'article')
        self.assertEqual(block_value[2].value, "heading 0")
        self.assertEqual(block_value[2].id, "0000") 
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_block_counts_min_validation_errors(self):
        class ValidatedBlock(blocks.StreamBlock):
            char = blocks.CharBlock()
            url = blocks.URLBlock()
        block = ValidatedBlock(block_counts={'char': {'min_num': 1}})

        value = blocks.StreamValue(block, [
            ('url', 'http://example.com/'),
            ('url', 'http://example.com/'),
        ])

        with self.assertRaises(ValidationError) as catcher:
            block.clean(value)
        self.assertEqual(catcher.exception.params, {
            '__all__': ['Char: The minimum number of items is 1']
        })

        # a value with 1 char block should pass validation
        value = blocks.StreamValue(block, [
            ('url', 'http://example.com/'),
            ('char', 'foo'),
            ('url', 'http://example.com/'),
        ])
        self.assertTrue(block.clean(value)) 
Example #13
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_max_num_validation_errors(self):
        class ValidatedBlock(blocks.StreamBlock):
            char = blocks.CharBlock()
            url = blocks.URLBlock()
        block = ValidatedBlock(max_num=1)

        value = blocks.StreamValue(block, [
            ('char', 'foo'),
            ('char', 'foo'),
            ('url', 'http://example.com/'),
            ('url', 'http://example.com/'),
        ])

        with self.assertRaises(ValidationError) as catcher:
            block.clean(value)
        self.assertEqual(catcher.exception.params, {
            '__all__': ['The maximum number of items is 1']
        })

        # a value with 1 block should pass validation
        value = blocks.StreamValue(block, [('char', 'foo')])
        self.assertTrue(block.clean(value)) 
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_min_num_validation_errors(self):
        class ValidatedBlock(blocks.StreamBlock):
            char = blocks.CharBlock()
            url = blocks.URLBlock()
        block = ValidatedBlock(min_num=1)

        value = blocks.StreamValue(block, [])

        with self.assertRaises(ValidationError) as catcher:
            block.clean(value)
        self.assertEqual(catcher.exception.params, {
            '__all__': ['The minimum number of items is 1']
        })

        # a value with >= 1 blocks should pass validation
        value = blocks.StreamValue(block, [('char', 'foo')])
        self.assertTrue(block.clean(value)) 
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 ArticleBlock(blocks.StreamBlock):
            heading = blocks.CharBlock()
            paragraph = blocks.CharBlock()

        block = ArticleBlock()
        value = block.to_python([
            {
                'type': 'heading',
                'value': "My title",
                'id': '123123123',
            },
            {
                'type': 'paragraph',
                'value': 'My first paragraph',
            },
            {
                'type': 'paragraph',
                'value': 'My second paragraph',
            },
        ])
        return block.render_form(value, prefix='myarticle') 
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_on_stream_child_uses_child_template(self):
        """
        Accessing a child element of the stream (giving a StreamChild object) and rendering it
        should use the block template, not just render the value's string representation
        """
        block = blocks.StreamBlock([
            ('heading', blocks.CharBlock(template='tests/blocks/heading_block.html')),
            ('paragraph', blocks.CharBlock()),
        ])
        value = block.to_python([
            {'type': 'heading', 'value': 'Hello'}
        ])
        html = value[0].render()
        self.assertEqual('<h1>Hello</h1>', html)

        # StreamChild.__str__ should do the same
        html = str(value[0])
        self.assertEqual('<h1>Hello</h1>', html)

        # and so should StreamChild.render_as_block
        html = value[0].render_as_block()
        self.assertEqual('<h1>Hello</h1>', html) 
Example #17
Source File: test_jinja2.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_rich_text_is_safe(self):
        """
        Ensure that RichText values are marked safe
        so that they don't get double-escaped when inserted into a parent template (#2542)
        """
        stream_block = blocks.StreamBlock([
            ('paragraph', blocks.RichTextBlock(template='tests/jinja2/rich_text.html'))
        ])
        stream_value = stream_block.to_python([
            {'type': 'paragraph', 'value': '<p>Merry <a linktype="page" id="4">Christmas</a>!</p>'},
        ])

        result = render_to_string('tests/jinja2/stream.html', {
            'value': stream_value,
        })

        self.assertIn('<p>Merry <a href="/events/christmas/">Christmas</a>!</p>', result) 
Example #18
Source File: test_jinja2.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_include_block_tag_with_streamvalue(self):
        """
        The include_block tag should be able to render a StreamValue's template
        while keeping the parent template's context
        """
        block = blocks.StreamBlock([
            ('heading', blocks.CharBlock(template='tests/jinja2/heading_block.html')),
            ('paragraph', blocks.CharBlock()),
        ], template='tests/jinja2/stream_with_language.html')

        stream_value = block.to_python([
            {'type': 'heading', 'value': 'Bonjour'}
        ])

        result = render_to_string('tests/jinja2/include_block_test.html', {
            'test_block': stream_value,
            'language': 'fr',
        })

        self.assertIn('<div class="heading" lang="fr"><h1 lang="fr">Bonjour</h1></div>', result) 
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_render_passes_context_to_children(self):
        block = blocks.StreamBlock([
            ('heading', blocks.CharBlock(template='tests/blocks/heading_block.html')),
            ('paragraph', blocks.CharBlock()),
        ])
        value = block.to_python([
            {'type': 'heading', 'value': 'Bonjour'}
        ])
        html = block.render(value, context={
            'language': 'fr',
        })
        self.assertIn('<div class="block-heading"><h1 lang="fr">Bonjour</h1></div>', html)

        # calling render_as_block(context=foo) on value (a StreamValue instance)
        # should be equivalent to block.render(value, context=foo)
        html = value.render_as_block(context={
            'language': 'fr',
        })
        self.assertIn('<div class="block-heading"><h1 lang="fr">Bonjour</h1></div>', html) 
Example #20
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_initialisation_with_mixins(self):
        """
        The order of child blocks of a ``StreamBlock`` with multiple parent
        classes is slightly surprising at first. Child blocks are inherited in
        a bottom-up order, by traversing the MRO in reverse. In the example
        below, ``ArticleWithIntroBlock`` will have an MRO of::

            [ArticleWithIntroBlock, IntroMixin, ArticleBlock, StreamBlock, ...]

        This will result in ``intro`` appearing *after* ``heading`` and
        ``paragraph`` in ``ArticleWithIntroBlock.child_blocks``, even though
        ``IntroMixin`` appeared before ``ArticleBlock``.
        """
        class ArticleBlock(blocks.StreamBlock):
            heading = blocks.CharBlock()
            paragraph = blocks.CharBlock()

        class IntroMixin(blocks.StreamBlock):
            intro = blocks.CharBlock()

        class ArticleWithIntroBlock(IntroMixin, ArticleBlock):
            by_line = blocks.CharBlock()

        block = ArticleWithIntroBlock()

        self.assertEqual(list(block.child_blocks.keys()),
                         ['heading', 'paragraph', 'intro', 'by_line']) 
Example #21
Source File: streamfield.py    From wagtail-torchbox with MIT License 5 votes vote down vote up
def serialise_block(self, block, value):
        if hasattr(block, 'to_graphql_representation'):
            return block.to_graphql_representation(value)
        elif isinstance(block, blocks.RichTextBlock):
            return serialize_rich_text(value.source)
        elif isinstance(block, EmbedBlock):
            try:
                embed = get_embed(value.url)
                return {
                    'html': embed.html,
                    'url': value.url,
                }
            except EmbedException:
                return {
                    'html': '',
                    'url': None
                }
        elif isinstance(block, ImageChooserBlock):
            # FIXME
            return {
                'id': value.id,
                'alt': value.title,
                'src': settings.MEDIA_PREFIX + value.file.url,
                'hash': value.get_file_hash()
            }
        elif isinstance(block, blocks.FieldBlock):
            return value
        elif isinstance(block, blocks.StructBlock):
            return self.serialise_struct_block(block, value)
        elif isinstance(block, blocks.ListBlock):
            return self.serialise_list_block(block, value)
        elif isinstance(block, blocks.StreamBlock):
            return self.serialise_stream_block(block, value) 
Example #22
Source File: fields.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, block_types, **kwargs):
        super().__init__(**kwargs)
        if isinstance(block_types, Block):
            self.stream_block = block_types
        elif isinstance(block_types, type):
            self.stream_block = block_types(required=not self.blank)
        else:
            self.stream_block = StreamBlock(block_types, required=not self.blank) 
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_initialisation(self):
        block = blocks.StreamBlock([
            ('heading', blocks.CharBlock()),
            ('paragraph', blocks.CharBlock()),
        ])

        self.assertEqual(list(block.child_blocks.keys()), ['heading', 'paragraph']) 
Example #24
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_name_cannot_contain_dashes(self):
        block = blocks.StreamBlock([
            ('heading', blocks.CharBlock()),
            ('rich-text', blocks.RichTextBlock()),
        ])

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

        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, block.child_blocks['rich text']) 
Example #26
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_name_must_be_nonempty(self):
        block = blocks.StreamBlock([
            ('heading', blocks.CharBlock()),
            ('', blocks.RichTextBlock()),
        ])

        errors = block.check()
        self.assertEqual(len(errors), 1)
        self.assertEqual(errors[0].id, 'wagtailcore.E001')
        self.assertEqual(errors[0].hint, "Block name cannot be empty")
        self.assertEqual(errors[0].obj, block.child_blocks['']) 
Example #27
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_initialisation_from_subclass(self):
        class ArticleBlock(blocks.StreamBlock):
            heading = blocks.CharBlock()
            paragraph = blocks.CharBlock()

        block = ArticleBlock()

        self.assertEqual(list(block.child_blocks.keys()), ['heading', 'paragraph']) 
Example #28
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_initialisation_from_subclass_with_extra(self):
        class ArticleBlock(blocks.StreamBlock):
            heading = blocks.CharBlock()
            paragraph = blocks.CharBlock()

        block = ArticleBlock([
            ('intro', blocks.CharBlock())
        ])

        self.assertEqual(list(block.child_blocks.keys()), ['heading', 'paragraph', 'intro']) 
Example #29
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_initialisation_with_multiple_subclassses(self):
        class ArticleBlock(blocks.StreamBlock):
            heading = blocks.CharBlock()
            paragraph = blocks.CharBlock()

        class ArticleWithIntroBlock(ArticleBlock):
            intro = blocks.CharBlock()

        block = ArticleWithIntroBlock()

        self.assertEqual(list(block.child_blocks.keys()), ['heading', 'paragraph', 'intro']) 
Example #30
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_value_from_datadict(self):
        class ArticleBlock(blocks.StreamBlock):
            heading = blocks.CharBlock()
            paragraph = blocks.CharBlock()

        block = ArticleBlock()

        value = block.value_from_datadict({
            'foo-count': '3',
            'foo-0-deleted': '',
            'foo-0-order': '2',
            'foo-0-type': 'heading',
            'foo-0-id': '0000',
            'foo-0-value': 'this is my heading',
            'foo-1-deleted': '1',
            'foo-1-order': '1',
            'foo-1-type': 'heading',
            'foo-1-id': '0001',
            'foo-1-value': 'a deleted heading',
            'foo-2-deleted': '',
            'foo-2-order': '0',
            'foo-2-type': 'paragraph',
            'foo-2-id': '',
            'foo-2-value': '<p>this is a paragraph</p>',
        }, {}, prefix='foo')

        self.assertEqual(len(value), 2)
        self.assertEqual(value[0].block_type, 'paragraph')
        self.assertEqual(value[0].id, '')
        self.assertEqual(value[0].value, '<p>this is a paragraph</p>')

        self.assertEqual(value[1].block_type, 'heading')
        self.assertEqual(value[1].id, '0000')
        self.assertEqual(value[1].value, 'this is my heading')