Skip to main content

🎛️ Custom widgets and formats

When no built-in widget or format fits a field, you can write your own. A custom widget or format is a React component in a JavaScript file in your static files. A Python class names the component and the file, and you use that class like a built-in one. The admin loads the file the first time a page shows the widget or format, so pages that don't use it never load it.

Your component uses the admin's own React and a set of its interface parts (inputs, buttons, selects and more), so it looks and behaves like the rest of the admin.

A custom widget​

Subclass CustomWidget and set two attributes:

  • component: the name your script registers the component under, such as "blog.FediverseHandle". Start it with a prefix of your own, so it can't clash with names from other apps.
  • js: the script's path in your static files, such as "blog/studio/components.js".
# blog/studio_widgets.py
from content_studio.widgets import CustomWidget


class FediverseHandleWidget(CustomWidget):
component = "blog.FediverseHandle"
js = "blog/studio/components.js"

Use it like any widget: on a Field, in default_widget_mapping, or as the widget_class of a model field.

# blog/admin.py
from content_studio import register
from content_studio.admin import ModelStudio
from content_studio.form import Field

from .models import Article
from .studio_widgets import FediverseHandleWidget


@register(Article)
class ArticleStudio(ModelStudio):
edit_main = [
"title",
"body",
Field("author_handle", widget=FediverseHandleWidget),
]

The script is a JavaScript module that registers the component with registerWidget. It imports react and the admin's modules by their names, and the admin provides them. Without a build step, createElement stands in for JSX:

// blog/static/blog/studio/components.js
import { createElement as h, useState } from "react";
import { registerWidget } from "@content-studio/admin";
import { Input } from "@content-studio/ui";

const HANDLE = /^@?[\w.]+@[\w-]+(\.[\w-]+)+$/;

function FediverseHandle({ value, onChange, id, setError, ...aria }) {
const [text, setText] = useState(value ?? "");

return h(Input, {
...aria,
id,
value: text,
placeholder: "@you@example.social",
onChange(event) {
const next = event.target.value.trim();
setText(event.target.value);
onChange(next);
setError(
next && !HANDLE.test(next) ? "Enter a handle like @you@example.social." : null,
);
},
});
}

registerWidget("blog.FediverseHandle", FediverseHandle);

The value is saved through the model field as usual, so the field's own validation still runs when you press Save.

What the component gets​

PropWhat it is
valueThe field's current value, or null when it is empty.
onChange(value)Reports a new value to the form. The value must be one the field's serializer accepts: text for a CharField, a number for an IntegerField, a JSON value for a JSONField.
optionsWhat the class's get_options() returned (see Options).
fieldThe model field: verbose_name, required, type (such as "CharField"), and help_text, max_length and choices (as [value, label] pairs) when it has them.
nameThe field's name on the model.
idThe id to give your input, so the field's label points to it.
aria-describedby, aria-invalidPass these to your input, so screen readers read the help text and errors.
errorThe message you set with setError, or null.
setError(message)Marks what the editor typed as not savable, or as fine again with null.

Refusing input that can't be saved​

Call setError with a message while the input can't be saved, such as a half-typed handle, and with null once it can. While a message is set, Save is blocked and the message shows under the field. Values you report with onChange in the meantime are kept, and the component gets them back as value. This is how the built-in JSON and code widgets refuse text that doesn't parse.

setError only keeps the form from sending the value. Check the value on the server too, with the model field's validators.

A custom format​

A custom format shows a value in table cells and in read-only fields. Subclass CustomFormat, set component and js, and register the component with registerFormat. One script can register several widgets and formats.

# blog/studio_widgets.py
from content_studio.formats import CustomFormat


class BarFormat(CustomFormat):
"""A number as a bar, full at max."""

component = "blog.Bar"
js = "blog/studio/components.js"

def __init__(self, *, max: int = 100):
if not isinstance(max, int) or max < 1:
raise ValueError(f"BarFormat max must be a positive int; got {max!r}.")
self.max = max

def get_options(self):
return {"max": self.max}
# blog/admin.py
from content_studio import register
from content_studio.admin import ModelStudio
from content_studio.form import TableColumn

from .models import Category
from .studio_widgets import BarFormat


@register(Category)
class CategoryStudio(ModelStudio):
table_display = [
"name",
TableColumn(field="article_count", header="Articles", format=BarFormat(max=10)),
]

def article_count(self, obj, request):
return obj.article_set.count()
// blog/static/blog/studio/components.js
import { createElement as h } from "react";
import { registerFormat } from "@content-studio/admin";

function Bar({ value, options, emptyValue }) {
if (value === null) {
return h("span", null, emptyValue ?? "");
}

const share = Math.min(1, value / options.max);

return h(
"span",
{ title: `${value} of ${options.max}` },
h("meter", { value: share }),
` ${value}`,
);
}

registerFormat("blog.Bar", Bar);
PropWhat it is
valueThe value, or null. For a method column, what the method returned.
optionsWhat the class's get_options() returned.
fieldThe model field, as for a widget. A method column has none.
display"cell" in a table, "field" in a read-only field on the edit page, which has more room.
emptyValueWhat to show for an empty value, such as a dash.

Options​

What get_options() returns reaches the component as its options prop. The values must be JSON-safe: strings, numbers, booleans, lists and dicts. Options set to None are left out. Check the options in __init__, as the built-in widgets do, so a mistake fails when Django starts and not in the editor's browser.

What the admin provides​

Your script imports these modules by name. They are the admin's own copies, so leave them out of your script and don't load another copy of React.

ModuleWhat it has
react, react/jsx-runtime, react-domThe admin's React.
@content-studio/adminregisterWidget(name, component), registerFormat(name, component), and useLanguage(), the editor's language in the admin (such as "en" or "pt-BR").
@content-studio/uiInput, Textarea, Button, Select (with SelectTrigger, SelectValue, SelectContent, SelectItem, SelectGroup, SelectLabel and SelectSeparator), Checkbox, Switch, Badge, Tooltip (with TooltipTrigger and TooltipContent), Popover (with PopoverTrigger, PopoverContent and PopoverAnchor), Dialog (with DialogTrigger, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription and DialogClose), Spinner and toast.

The admin's own class names may change between versions, so don't rely on them. Style your component with the parts above, inline styles or a stylesheet of your own. The theme's colors are CSS variables that follow light and dark mode, such as var(--foreground), var(--muted-foreground), var(--border), var(--primary) and var(--muted).

JSX and TypeScript​

For JSX or TypeScript, build the script with a bundler. Output an ES module and keep the admin's modules external, so they stay imports. With esbuild:

npx esbuild studio/components.tsx --bundle --format=esm --jsx=automatic \
--external:react --external:react-dom --external:@content-studio/* \
--outfile=blog/static/blog/studio/components.js

The type declarations of @content-studio/admin and @content-studio/ui ship with the package, at content_studio/static/content_studio/runtime/content-studio.d.ts. Copy the file into your project and install the React types of the same major version as the admin's React. CustomWidgetProps and CustomFormatProps type your components' props:

import { registerWidget, type CustomWidgetProps } from "@content-studio/admin";

function FediverseHandle({ value, onChange }: CustomWidgetProps<string>) {
return <input value={value ?? ""} onChange={(e) => onChange(e.target.value)} />;
}

registerWidget("blog.FediverseHandle", FediverseHandle);

When a component fails​

If the script doesn't load, doesn't register the name, or the component throws while it renders, the admin shows the value as read-only text and the rest of the page keeps working. With DEBUG on, the developer tools list the error.

The system check content_studio.E069 reports what it can find before the admin runs: CustomWidget or CustomFormat used without a subclass, a subclass that doesn't set component and js, a js file that no static files finder has, and one component name used for two different files.

Limits​

  • js is a path in your static files, not a URL: scripts load from your own site, like the admin itself.
  • Editing in the table uses the table's own cell controls, not custom widgets. A custom format still shows the value in the table.
  • A custom widget's value goes through the model field and its serializer unchanged, so it must be a value the field accepts.