Rich Text

This guide covers Proper's rich text addon - a field type that stores formatted documents with embedded attachments, plus a default editor that knows how to produce and edit them.

After reading this guide, you will know:

  • What rich text means in Proper, and how to install and configure it.
  • How to create, render, style, and customize rich text content.
  • How the bundled editor handles attachments.

The companion File Storage guide covers attachments at the level rich text builds on. Read it first if you haven't met the Attachment model.


1. Introduction

Proper's rich text addon stores and displays text that includes formatting beyond plain text, such as bold, italics, colors, hyperlinks, and tables.

It integrates the Lexxy rich text editor, which includes file uploads and image embedding out of the box. The editor can also be extended to add things like @mentions, emojis, or whatever other text feature your app needs.

Lexxy
The default rich text editor

2. Setup

To install the rich text addon, run:

$ proper install rich_text

It does the following:

  • Installs the storage addon, if it's not already, you need it for attachments.
  • Adds the js and css files for the Lexxy editor, and bin/vendor-lexxy.py, a script that downloads them again when you want to update the editor: change the versions in it and run uv run python bin/vendor-lexxy.py.
  • Creates the components for the editor and for rendering attachments.
  • Adds a task for cleaning up abandoned uploads.
  • Adds config/rich_text.py, with the settings of the sanitizer, and the nh3 library to the dependencies of your project.

If you turn on the Content-Security-Policy of your application, keep the parts of it that are for the editor: without them, the colors of a text are lost.

Now run the migrations to create the attachment and attachment_reference tables added by the storage addon.

$ proper db migrate

3. Creating Rich Text content

The rich text addon works with existing text fields so you don't need to create a database migration to add it to your models.

You do need, however, to update the python classes involved.

3.1 Models

Let's say you have a model like this:

models/post.py
import peewee as pw

from .base import BaseModel

class Post(BaseModel):
    title = pw.CharField()
    body = pw.TextField(null=True)

and you want to make the body rich-text. To do so, update the field type and add the HasRichText mixin:

models/post.py
import peewee as pw
from proper.rich_text import HasRichText, RichTextField

from .attachment import Attachment
from .base import BaseModel

# HasRichText must go before BaseModel
class Post(HasRichText, BaseModel):
    title = pw.CharField()
    body = RichTextField(Attachment, null=True)

As you see, you also need to pass your Attachment model to it, so it can load the embedded attachments when rendering.

Warning

HasRichText must be listed before BaseModel. Peewee's save() and delete_instance() don't call super(), so a mixin placed after the model class would never run: embedded files would have no references and be deleted later as abandoned uploads. Proper raises a TypeError when the class is defined in the wrong order, so you can't miss it.

If you don't want to use image/file uploads in that field, pass None instead and drop the mixin. The result is much simpler:

models/post.py
import peewee as pw
from proper.rich_text import RichTextField

from .base import BaseModel

class Post(BaseModel):
    title = pw.CharField()
    body = RichTextField(None, null=True)

3.2 Forms

Change your f.TextField into a f.RichTextField:

forms/post.py
from proper import forms as f

from myapp.models import Post

class PostForm(f.Form):
    class Meta:
        orm_cls = Post

    title = f.TextField()
    body = f.RichTextField(required=False)

f.RichTextField is a thin subclass of f.TextField that knows how to coerce a RichTextDocument (the runtime value of a RichTextField model column) into the HTML string the form needs to render and submit.

3.3 Views

Finally you need to render the editor. The addon created a component for it, you just have to import it and use it:

views/post/form.jx
{#import "form.jx" as Form #}
{#import "rich_text_editor.jx" as RichTextEditor #}
{#js "js/nestedform.js" #}
{#def form, action='', method='post' #}

<Form method={{ method }} action={{ action }}>
  <div class="field">
    {{ form.title.label("Title") }}
    {{ form.title.text_input() }}
    {{ form.title.error_tag() }}
  </div>
  <div class="field">
    {{ form.body.label("Body") }}
    <RichTextEditor field={{ form.body }}></RichTextEditor>
    {{ form.body.error_tag() }}
  </div>
  {{ content }}
</Form>

The editor has many ways to customize it - adding or removing features, editing the toolbar buttons, etc. - you will read about it in the Customizing the Editor section.


4. Rendering Rich Text content

The value of a rich_text.RichTextField can be directly embedded into a page, because it sanitizes its content when it is rendered. You can display the content as follows:

{{ post.body }}

RichTextDocument.__html__ transforms the data into a sanitized HTML string, including attachments. On the other hand, RichTextDocument.__str__ returns the text without HTML tags, useful for metadata or search indexes: paragraphs separated by a blank line, - before each list item, links followed by their address in parentheses, and images and attachments as their alt text (or file name) in brackets.

You probably also want to include the lexxy-content.css stylesheet - to give your content the same styles it has in the editor - and to wrap the field with a lexxy-content class, since that's what the styles use:

{#css css/lexxy-content.css #}

<div class="lexxy-content">
  {{ post.body }}
</div>

4.1 Sanitizing

The HTML of a document comes from a form, so it can be anything: the editor cleans what is pasted into it, but nothing stops someone from sending a request with a <script> tag in it. That's why the HTML is sanitized on the server, every time a document is rendered. Only the tags, attributes, CSS properties and URL schemes of an allowlist are kept; the rest is removed.

The allowlist lives in config/rich_text.py:

Setting Description
RICH_TEXT_SANITIZE True by default. False renders the documents as they are stored.
RICH_TEXT_ALLOWED_TAGS List of the tags that are kept.
RICH_TEXT_ALLOWED_ATTRIBUTES Dict of tag name to the list of its allowed attributes. The ones under "*" are allowed in every tag.
RICH_TEXT_ALLOWED_STYLES List of the CSS properties kept in a style attribute.
RICH_TEXT_ALLOWED_URL_SCHEMES List of the URL schemes allowed in attributes like href and src. Relative URLs are always allowed.

The installed file allows what the editor can produce. If you add a feature to the editor that writes other tags or attributes, add them to these lists too. For example, to let the documents have links that open in a new tab:

RICH_TEXT_ALLOWED_ATTRIBUTES = {
    ...
    "a": ["href", "target"],
}

Some things to know:

  • What is stored is never changed. The sanitizer runs when the document is rendered, so a change in these settings applies to every document, old and new, and nothing is lost if you allow more later.
  • Links get rel="noopener noreferrer", unless you add rel to the allowed attributes of a.
  • The <proper-attachment> tags are always kept, and the output of the rich_text_attachment.jx component isn't sanitized: it's your code.
  • Don't allow data-controller or data-action. A document could then run the Stimulus controllers of your app.
  • Only {{ post.body }} is sanitized. post.body.to_html() returns the HTML as it is stored. If you need the sanitized HTML as a string, with the attachment tags still in place, use post.body.to_safe_html().

Turning the sanitizer off

With RICH_TEXT_SANITIZE = False, whoever can write a document can run JavaScript in the browser of whoever reads it. Do it only if every author of rich text in your app is trusted, like in a back-office with a few known editors.

An app that had the addon before the sanitizer existed doesn't have config/rich_text.py: the defaults are used, and you only need to add nh3 to its dependencies (uv add nh3).

4.2 Rendering embedded images and attachments

The HTML code stored in the database by a rich_text.RichTextField uses special <proper-attachment> tags to reference attachments (instead of <img> tags).

On rendering, the UUIDs of the attachments are collected, loaded in a single query, and rendered to HTML using the views/rich_text_attachment.jx component, added to your application by the addon.

You can customize how to render attachments editing that file. It receives:

  • attachment - the resolved Attachment row.
  • alt, caption - the text the user typed for this embed in the editor.
  • Any other attribute the editor wrote on the placeholder tag.

For example, here is a version that renders videos using a <video> tag, resizes images to 800 pixels, and falls back to a plain download link for everything else:

views/rich_text_attachment.jx
{#def attachment, alt: str = "", caption: str = "" #}

{% if attachment.content_type.startswith("video/") %}
  <video controls src="{{ attachment.url }}"></video>
{% elif attachment.is_previewable %}
  {% set variant = attachment.variant(resize_to_limit=(800, 800)) %}
  <figure>
    <img src="{{ variant.url }}" alt="{{ alt }}" loading="lazy">
    {% if caption %}<figcaption>{{ caption }}</figcaption>{% endif %}
  </figure>
{% else %}
  <a href="{{ attachment.url }}">{{ attachment.filename }}</a>
{% endif %}

See the File Storage guide for details on variant(), previewable content types, and how to add support for new ones.


5. Customizing the Editor

Depending on where you are using the editor, you might want to disable some features, enable others, or update the presentation of the editor.

5.1 Customizing the editor features

At minimum, you render the editor component like this:

{#import "rich_text_editor.jx" as RichTextEditor #}

<RichTextEditor field={{ form.myfield }}></RichTextEditor>

The rich_text_editor.jx component declares these options in its {#def}, so they're handled by the component itself:

Option Description
toolbar Pass "false" (as a string) to disable the toolbar entirely. By default, the toolbar is rendered using the rich_text_toolbar.jx component.
toolbar-upload Control which upload button(s) appear in the toolbar. Accepts "file", "image", or "both" (default). The image button restricts the file picker to images and videos (accept="image/*,video/*"), which triggers the native photo/video picker on iOS and Android. The file button opens an unrestricted file picker.
markdown Pass "true" (as a string) to enable Markdown support.

Every other attribute you set on <RichTextEditor> passes straight through to the underlying <lexxy-editor> element, which reads them as kebab-cased HTML attributes. That includes the Lexxy editor attributes below:

Attribute Description
attachments Pass "false" (as a string) to disable attachments completely. By default, attachments are supported, including paste and drag & drop support. For finer-grained control - keeping attachments enabled while restricting which content types are accepted - use permitted-attachment-types.
multi-line Pass "false" (as a string) to force single line editing.
permitted-attachment-types Restrict the editor to a specific allowlist of attachment content types. Unset (the default) permits any content type. Example: <RichTextEditor permitted-attachment-types="application/epub+zip application/pdf" field={{form.body}} />.

...as well as standard HTML attributes like placeholder, class, disabled, autofocus, etc.

5.2 Customizing the toolbar

The toolbar is rendered using the views/rich_text_toolbar.jx component, added by the addon to your application.

In there you can update classes, replace the button icons, and add or remove buttons.

Beware that removing a button doesn't mean removing the ability to use the format. Files/images can be uploaded by drag-and-drop (use the attachments option to disable them), and many formats have standard keyboard shortcuts that will still work: ctrl+b for bold, ctrl+i for italics, ctrl+k for adding links, etc.


6. Extending the editor

"Prompts" is the Lexxy mechanism that lets you implement features like @mentions, /commands, or any other trigger-based suggestions. When you select an item from the prompt, you have two options:

A. Insert the item as a custom attachment. Proper's renderer resolves attachments only against your Attachment model and drops the ones it can't resolve, so this option is not supported out of the box. B. Insert the item as free text in the editor.

Lexxy also lets you configure how to load the items: inline or remotely, and how to do the filtering (locally or on the server).

6.1 Free HTML attachments

This is the simplest type of prompt: it inserts the prompt item HTML directly in the editor. This is useful for things like hashtags, emojis, or other inline elements that don't require server-side processing.

To enable these, you must add the insert-editable-text attribute to the <lexxy-prompt> element:

<RichTextEditor field={{post.body}}>

  <lexxy-prompt trigger=":" insert-editable-text>
    <lexxy-prompt-item search="joy laughing face">
      <template type="menu">πŸ˜‚ :joy</template>
      <template type="editor">πŸ˜‚</template>
    </lexxy-prompt-item>
    <lexxy-prompt-item search="heart red heart">
      <template type="menu">❀️ :heart</template>
      <template type="editor">❀️</template>
    </lexxy-prompt-item>
    <lexxy-prompt-item search="+1 thumbs up like">
      <template type="menu">πŸ‘ :+1</template>
      <template type="editor">πŸ‘</template>
    </lexxy-prompt-item>
    <lexxy-prompt-item search="tada party popper celebration">
      <template type="menu">πŸŽ‰ :tada</template>
      <template type="editor">πŸŽ‰</template>
    </lexxy-prompt-item>
  </lexxy-prompt>

</RichTextEditor>

Typing the trigger is what makes the menu appear.

Emoji picker
Just like that, an emoji picker

When configured like this, if you select an item from the prompt, the content of the <template type="editor"> will be inserted directly in the editor as HTML you can edit freely (as long as the HTML is compatible with the tags that Lexxy supports).


7. Attachments

An "attachment" inside a rich text document is any file the user drops into the editor: an image they paste, a PDF they upload, a video clip, a spreadsheet. The bytes live wherever your storage service is configured to put them; the document just holds a small placeholder tag pointing at the Attachment row.

The placeholder looks like this in the stored HTML:

<proper-attachment sgid="0193c9f7a4b84c6e9f1d2e3a4b5c6d7e"
  caption="A picture of my cat"></proper-attachment>

That is all that gets stored: the attachment's ID and what the author typed (alt, caption, how it's presented). The editor also writes attributes that only restate facts about the file, like its URL, filename, content type and size. Proper drops those before saving and rebuilds them from the Attachment row every time the document is loaded into the editor.

The reason is the URL. It carries a token signed with your SECRET_KEYS, so a stored copy would stop working the day you copy the database to another environment or replace the keys, and the editor would show broken images. Because the URL is never stored, documents are valid anywhere, and there is nothing to migrate when keys change.

This section walks through how those rows get created, how Proper knows which records use them, when they get cleaned up, and how to work with them from your Python code.

7.1 The attachment lifecycle

Unlike a regular form field, the editor uploads files before the user submits the form. The flow looks like this:

  1. The user drops a file into the editor (or clicks the upload button).
  2. The browser POSTs the file's metadata to your app's DirectUpload.create endpoint. An Attachment row is created with the source of that controller, "rich_text", and the server returns a signed URL.
  3. The browser PUTs the file bytes directly to storage using that URL.
  4. The editor inserts a <proper-attachment sgid="..."> placeholder in the document.
  5. When the user submits the form, the parent model's save() records that this record embeds the attachment.

Until step 5 happens, no record embeds the row: it is provisional. The user might close the tab, hit "back", or just walk away. The sweeper job described below cleans up rows that nobody embeds for too long.

7.2 Who uses each attachment

Proper keeps a table, attachment_reference, with one row for each record and rich text column that embeds an attachment. The model is Attachment.Reference, exported as AttachmentReference by models/attachment.py so that proper db create makes its table. You don't write to it: HasRichText does.

Two records can embed the same attachment. Copying a post copies its HTML, and the images inside it, without copying the files; each version of a versioned document is a new row with the same HTML. The attachment is purged only when the last record that embeds it lets it go.

From an attachment, is_referenced says whether some record embeds it, and references lists the rows:

att.is_referenced  # True or False
for ref in att.references:
    print(ref.record_type, ref.record_id, ref.field)  # "post", "42", "body"

7.3 Save and delete behavior

The HasRichText mixin (which you added to your model in the Models section) hooks into two events:

On save, for each rich text column, the mixin compares the attachments in the new body with the references of the record:

  • Adds a reference for every attachment that is new in the body. The upload now has a home and the sweeper will leave it alone.
  • Removes the reference of every attachment that was in the body but is no longer there, and schedules a purge for the ones that no other record embeds. Editing a post to remove an image frees its storage automatically, unless a copy of the post still shows it.

On delete, the mixin removes every reference of the record and schedules a purge for the attachments left without any. Tearing down a post tears down its embedded files too, unless another record embeds them.

Purges are dispatched as background jobs, so they don't block the save or the user's request. If your record has multiple RichTextField columns, the mixin handles them all without extra configuration.

Deleting a record with a query doesn't run the hooks. Release its attachments first:

post.release_rich_text_attachments()
Post.delete().where(Post.id == post.id).execute()

This removes the references of the record and purges the attachments that no other record embeds, the same as delete_instance() does.

Rows deleted by the database, with an ON DELETE CASCADE, or by a query without releasing them, leave references to records that no longer exist. Rows changed with Model.update() have references that don't match their bodies. rebuild_rich_text_references() repairs both for the models you give it, and is also how you fill the table for records that exist from before:

from proper.rich_text import rebuild_rich_text_references

rebuild_rich_text_references(Post, Comment)

It doesn't purge anything. An attachment left without references is swept by the task below once it is older than the grace period.

Composite primary keys are not supported: record_id holds the primary key as a single string.

7.4 Sweeping abandoned uploads

Pre-uploaded files that no record ever embeds are orphans. They take up storage with no document pointing at them. The rich-text addon generates a periodic task that sweeps these up:

tasks/abandoned_uploads_sweep.py
from huey import crontab
from proper.rich_text import purge_abandoned_uploads

from myapp.main import app
from myapp.models import Attachment


@app.queue.periodic_task(crontab(hour="3", minute="0"))
def sweep_abandoned_uploads():
    purge_abandoned_uploads(Attachment, grace_hours=24)

By default it runs at 3 AM each day and purges any row with source="rich_text" that is older than 24 hours and that no record embeds. Variants are skipped: they go with their parent. Tune the crontab and grace_hours to taste:

  • A short grace period reclaims storage faster but risks deleting an upload while the user is still composing a long post.
  • A long grace period is gentler on users but keeps orphans around longer.

The sweep only touches rows where source="rich_text". A file sent with a form or attached from code has an empty source and no references, and is in use: it is never swept. Other addons that pre-upload with their own lifecycle policy, and their own source, aren't affected either.

7.5 Accessing attachments from Python

A RichTextDocument (the runtime value of a RichTextField column) exposes the attachments it references:

post = Post.get(slug="my-post")

# All attachments in document order, deduplicated, fetched in one query.
for att in post.body.attachments:
    print(att.filename, att.content_type, att.byte_size)

The list is loaded lazily on first access and cached for the lifetime of the document instance, so reading post.body.attachments more than once does not hit the database again.

This is useful for things like building a gallery of every image in a post, picking a thumbnail for an OpenGraph tag, or feeding attachment metadata into an external search index.