Python wagtail.core.blocks.CharBlock() Examples

The following are 30 code examples of wagtail.core.blocks.CharBlock(). 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_html_declarations_uses_default(self):
        class ArticleBlock(blocks.StreamBlock):
            heading = blocks.CharBlock(default="Fish found on moon")
            paragraph = blocks.CharBlock(default="Lorem ipsum dolor sit amet")

        block = ArticleBlock()
        html = block.html_declarations()

        self.assertTagInTemplateScript(
            (
                '<input id="__PREFIX__-value" name="__PREFIX__-value" placeholder="Heading"'
                ' type="text" value="Fish found on moon" />'
            ),
            html
        )
        self.assertTagInTemplateScript(
            (
                '<input id="__PREFIX__-value" name="__PREFIX__-value" placeholder="Paragraph" type="text"'
                ' value="Lorem ipsum dolor sit amet" />'
            ),
            html
        ) 
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_form_handling_is_independent_of_serialisation(self):
        class Base64EncodingCharBlock(blocks.CharBlock):
            """A CharBlock with a deliberately perverse JSON (de)serialisation format
            so that it visibly blows up if we call to_python / get_prep_value where we shouldn't"""

            def to_python(self, jsonish_value):
                # decode as base64 on the way out of the JSON serialisation
                return base64.b64decode(jsonish_value)

            def get_prep_value(self, native_value):
                # encode as base64 on the way into the JSON serialisation
                return base64.b64encode(native_value)

        block = Base64EncodingCharBlock()
        form_html = block.render_form('hello world', 'title')
        self.assertIn('value="hello world"', form_html)

        value_from_form = block.value_from_datadict({'title': 'hello world'}, {}, 'title')
        self.assertEqual('hello world', value_from_form) 
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_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 #4
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 #5
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 #6
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_meta_nested_inheritance(self):
        """
        Check that having a multi-level inheritance chain works
        """
        class HeadingBlock(blocks.CharBlock):
            class Meta:
                template = 'heading.html'
                test = 'Foo'

        class SubHeadingBlock(HeadingBlock):
            class Meta:
                template = 'subheading.html'

        block = SubHeadingBlock()
        self.assertEqual(block.meta.template, 'subheading.html')
        self.assertEqual(block.meta.test, 'Foo') 
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(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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #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_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 #15
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 #16
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_api_representation_calls_same_method_on_children_with_context(self):
        """
        The get_api_representation method of a ListBlock should invoke
        the block's get_api_representation method on each child and
        the context should be passed on.
        """
        class ContextBlock(blocks.CharBlock):
            def get_api_representation(self, value, context=None):
                return context[value]

        block = blocks.ListBlock(
            ContextBlock()
        )
        api_representation = block.get_api_representation(["en", "fr"], context={
            'en': 'Hello world!',
            'fr': 'Bonjour le monde!'
        })

        self.assertEqual(
            api_representation, ['Hello world!', 'Bonjour le monde!']
        ) 
Example #17
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 #18
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 #19
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_uses_default(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock(default="Github")
            link = blocks.URLBlock(default="http://www.github.com")

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

        self.assertTagInTemplateScript(
            (
                '<input id="__PREFIX__-value-title" name="__PREFIX__-value-title" placeholder="Title"'
                ' type="text" value="Github" />'
            ),
            html
        )
        self.assertTagInTemplateScript(
            (
                '<input id="__PREFIX__-value-link" name="__PREFIX__-value-link" placeholder="Link"'
                ' type="url" value="http://www.github.com" />'
            ),
            html
        ) 
Example #20
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 #21
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 #22
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 #23
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_render_calls_block_render_on_children(self):
        """
        The default rendering of a StreamBlock should invoke the block's render method
        on each child, rather than just outputting the child value as a string.
        """
        block = blocks.StreamBlock([
            ('heading', blocks.CharBlock(template='tests/blocks/heading_block.html')),
            ('paragraph', blocks.CharBlock()),
        ])
        value = block.to_python([
            {'type': 'heading', 'value': 'Hello'}
        ])
        html = block.render(value)
        self.assertIn('<div class="block-heading"><h1>Hello</h1></div>', html)

        # calling render_as_block() on value (a StreamValue instance)
        # should be equivalent to block.render(value)
        html = value.render_as_block()
        self.assertIn('<div class="block-heading"><h1>Hello</h1></div>', html) 
Example #24
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 #25
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 #26
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_validation_errors(self):
        class ValidatedBlock(blocks.StreamBlock):
            char = blocks.CharBlock()
            url = blocks.URLBlock()
        block = ValidatedBlock()

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

        with self.assertRaises(ValidationError) as catcher:
            block.clean(value)
        self.assertEqual(catcher.exception.params, {
            0: ['This field is required.'],
            3: ['Enter a valid URL.'],
        }) 
Example #27
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 #28
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 #29
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 #30
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'])