Adding code and code blocks to StreamField in Wagtail

Wagtail's flexible StreamField facilitates many types of content. In this tutorial we will add inline code and code blocks.

July 9, 2020, 9:57 a.m.
Themes: Wagtail Streamfield options

Our starting point is a working Wagtail site with a StreamField. To the paragraph block of your StreamField add a features keyword to specify the features that we want in our text block, in this case because we want the code feature, which is not there by default:

('paragraph', blocks.RichTextBlock(features=['h1', 'h2', 'h3', 'h4', 'h5', 'bold', 'italic', 'ol', 'ul', 'hr', 'link', 'image', 'code', 'blockquote'])),

This will add the option of inline code. To facilitate code blocks, we install the package Wagtail Code Block:

pip3 install wagtailcodeblock

To create the option of a code block, add to our StreamField:

('code', CodeBlock(label=_("Code"))),

and import CodeBlock:

from wagtailcodeblock.blocks import CodeBlock

Wagtail Code Block features syntax highlighting as well. You can choose the themes and languages as described in the documentation, for example:

    ('bash', 'Bash/Shell'),
    ('css', 'CSS'),
    ('html', 'HTML'),
    ('javascript', 'Javascript'),
    ('json', 'JSON'),
    ('python', 'Python'),
    ('sql', 'SQL'),
    ('yaml', 'YAML'),

If you want to adjust Wagtail's styling of inline code to that of Wagtail Code Block, you can add the styling to the CSS file, e.g.:

code {
    background-color: #F3F0EE;
    padding: 2px;

One final thing: Wagtail Code Block uses line numbers by default. For smaller code snippets this might be overdoing it. In the documentation there seems to be no setting to switch this off. If you would like to do so, putting the following in your project's Javascript file should work:


Migrate the database to incorporate all the model changes and go to your editor to add some code to your pages.

We'll leave the article page alone for now. If you would like to categorize your articles in themes and create theme pages, read on.

Comment on this article (sign in first or confirm by name and email below)