Python wagtail.core.blocks.RichTextBlock() Examples

The following are 27 code examples of wagtail.core.blocks.RichTextBlock(). 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_rich_text.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_features_list_on_rich_text_block(self):
        block = RichTextBlock(features=['quotation', 'embed', 'made-up-feature'])

        form_html = block.render_form(block.to_python("<p>hello</p>"), 'body')

        # Check that the custom plugin options are being passed in the hallo initialiser
        self.assertIn('"halloquotation":', form_html)
        self.assertIn('"hallowagtailembeds":', form_html)
        self.assertNotIn('"hallolists":', form_html)
        self.assertNotIn('"hallowagtailimage":', form_html)

        # check that media (js/css) from the features is being imported
        media_html = str(block.media)
        self.assertIn('testapp/js/hallo-quotation.js', media_html)
        self.assertIn('testapp/css/hallo-quotation.css', media_html)
        # check that we're NOT importing media for the default features we're not using
        self.assertNotIn('wagtaildocs/js/hallo-plugins/hallo-wagtaildoclink.js', media_html) 
Example #2
Source File: fields.py    From developer-portal with Mozilla Public License 2.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        if "default" not in kwargs:
            kwargs["default"] = None

        super().__init__(
            [
                ("paragraph", RichTextBlock(features=RICH_TEXT_FEATURES)),
                ("image", ImageChooserBlock()),
                ("button", ButtonBlock()),
                ("embed", EmbedBlock()),
                (
                    "embed_html",
                    RawHTMLBlock(
                        help_text=(
                            "Warning: be careful what you paste here, since this "
                            "field could introduce XSS (or similar) bugs. "
                            "This field is meant solely for third-party embeds."
                        )
                    ),
                ),
                ("code_snippet", CodeSnippetBlock()),
            ],
            **kwargs
        ) 
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_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 #7
Source File: views.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def should_display(self, field):
        return not isinstance(field.block, (RecommendationBlock, RecommendationCommentsBlock, RichTextBlock)) 
Example #8
Source File: test_rich_text.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_custom_editor_in_rich_text_block(self):
        block = RichTextBlock(editor='custom')

        form_html = block.render_form(block.to_python("<p>hello</p>"), 'body')

        # Check that the custom plugin options are being passed in the hallo initialiser
        self.assertIn('makeHalloRichTextEditable("body", {"halloheadings": {"formatBlocks": ["p", "h2"]}});', form_html) 
Example #9
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 #10
Source File: test_streamfield.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_system_check_validates_block(self):
        class InvalidStreamModel(models.Model):
            body = StreamField([
                ('heading', blocks.CharBlock()),
                ('rich text', blocks.RichTextBlock()),
            ])

        errors = InvalidStreamModel.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, InvalidStreamModel._meta.get_field('body')) 
Example #11
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 #12
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 #13
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 #14
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_article(self, data):
        class ArticleBlock(blocks.StreamBlock):
            heading = blocks.CharBlock()
            paragraph = blocks.RichTextBlock()

        block = ArticleBlock()
        value = block.to_python(data)

        return block.render(value) 
Example #15
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_searchable_content(self):
        block = blocks.RichTextBlock()
        value = RichText(
            '<p>Merry <a linktype="page" id="4">Christmas</a>! &amp; a happy new year</p>\n'
            '<p>Our Santa pet <b>Wagtail</b> has some cool stuff in store for you all!</p>'
        )
        result = block.get_searchable_content(value)
        self.assertEqual(
            result, [
                'Merry Christmas! & a happy new year\n'
                'Our Santa pet Wagtail has some cool stuff in store for you all!'
            ]
        ) 
Example #16
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_validator(self):
        def validate_contains_foo(value):
            if 'foo' not in value:
                raise ValidationError("Value must contain 'foo'")

        block = blocks.RichTextBlock(validators=[validate_contains_foo])

        with self.assertRaises(ValidationError):
            block.clean(RichText('<p>bar</p>')) 
Example #17
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_validate_non_required_richtext_block(self):
        block = blocks.RichTextBlock(required=False)
        result = block.clean(RichText(''))
        self.assertIsInstance(result, RichText)
        self.assertEqual(result.source, '') 
Example #18
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_validate_required_richtext_block(self):
        block = blocks.RichTextBlock()

        with self.assertRaises(ValidationError):
            block.clean(RichText('')) 
Example #19
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_render_form(self):
        """
        render_form should produce the editor-specific rendition of the rich text value
        (which includes e.g. 'data-linktype' attributes on <a> elements)
        """
        block = blocks.RichTextBlock(editor='hallo')
        value = RichText('<p>Merry <a linktype="page" id="4">Christmas</a>!</p>')
        result = block.render_form(value, prefix='richtext')
        self.assertIn(
            (
                '&lt;p&gt;Merry &lt;a data-linktype=&quot;page&quot; data-id=&quot;4&quot;'
                ' data-parent-id=&quot;3&quot; href=&quot;/events/christmas/&quot;&gt;Christmas&lt;/a&gt;!&lt;/p&gt;'
            ),
            result
        ) 
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_get_default_with_richtext_value(self):
        default_value = blocks.RichTextBlock(default=RichText('<p>foo</p>')).get_default()
        self.assertIsInstance(default_value, RichText)
        self.assertEqual(default_value.source, '<p>foo</p>') 
Example #21
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_default_with_nonempty_string(self):
        default_value = blocks.RichTextBlock(default='<p>foo</p>').get_default()
        self.assertIsInstance(default_value, RichText)
        self.assertEqual(default_value.source, '<p>foo</p>') 
Example #22
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_default_with_empty_string(self):
        default_value = blocks.RichTextBlock(default='').get_default()
        self.assertIsInstance(default_value, RichText)
        self.assertEqual(default_value.source, '') 
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_get_default_with_default_none(self):
        default_value = blocks.RichTextBlock(default=None).get_default()
        self.assertIsInstance(default_value, RichText)
        self.assertEqual(default_value.source, '') 
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_get_default_with_fallback_value(self):
        default_value = blocks.RichTextBlock().get_default()
        self.assertIsInstance(default_value, RichText)
        self.assertEqual(default_value.source, '') 
Example #25
Source File: compare.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_comparison_class_for_block(block):
    if hasattr(block, 'get_comparison_class'):
        return block.get_comparison_class()
    elif isinstance(block, (blocks.CharBlock, blocks.TextBlock)):
        return CharBlockComparison
    elif isinstance(block, blocks.RawHTMLBlock):
        # Compare raw HTML blocks as if they were plain text, so that tags are shown explicitly
        return CharBlockComparison
    elif isinstance(block, blocks.RichTextBlock):
        return RichTextBlockComparison
    elif isinstance(block, blocks.StructBlock):
        return StructBlockComparison
    else:
        # As all stream field blocks have a HTML representation, fall back to diffing that.
        return RichTextBlockComparison 
Example #26
Source File: test_rich_text.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_custom_features_option_on_rich_text_block(self):
        block = RichTextBlock(editor='custom')

        form_html = block.render_form(block.to_python("<p>hello</p>"), 'body')

        # Check that the custom plugin options are being passed in the hallo initialiser
        self.assertIn('"halloquotation":', form_html)
        self.assertIn('"hallowagtailimage":', form_html)
        self.assertNotIn('"hallowagtailembeds":', form_html)
        self.assertNotIn('"hallolists":', form_html)

        # a 'features' list passed on the RichTextBlock
        # should override the list in OPTIONS
        block = RichTextBlock(editor='custom', features=['quotation', 'embed'])

        form_html = block.render_form(block.to_python("<p>hello</p>"), 'body')

        self.assertIn('"halloquotation":', form_html)
        self.assertIn('"hallowagtailembeds":', form_html)
        self.assertNotIn('"hallowagtailimage":', form_html)
        self.assertNotIn('"hallolists":', form_html)

        # check that media (js/css) from the features is being imported
        media_html = str(block.media)
        self.assertIn('testapp/js/hallo-quotation.js', media_html)
        self.assertIn('testapp/css/hallo-quotation.css', media_html)
        # check that we're NOT importing media for the default features we're not using
        self.assertNotIn('wagtaildocs/js/hallo-plugins/hallo-wagtaildoclink.js', media_html) 
Example #27
Source File: test_rich_text.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_features_option_on_rich_text_block(self):
        # a 'features' list passed on the RichTextBlock
        # should override the list in OPTIONS
        block = RichTextBlock(features=['h2', 'embed'])

        form_html = block.render_form(block.to_python("<p>hello</p>"), 'body')

        self.assertIn('"type": "header-two"', form_html)
        self.assertIn('"type": "EMBED"', form_html)
        self.assertNotIn('"type": "IMAGE""', form_html)
        self.assertNotIn('"type": "ordered-list-item""', form_html)