tempest_fastapi_sdk.ui.forms¶
Formulários gerados de schemas Pydantic e lidos de volta para eles.
form_for
¶
form_for(
schema: type[BaseModel],
*,
action: str,
method: str = "post",
values: Mapping[str, Any] | None = None,
errors: Mapping[str, Sequence[str]] | None = None,
include: Sequence[str] = (),
exclude: Sequence[str] = (),
submit_label: str = "Enviar",
submit: bool = True,
form_errors: Sequence[str] = (),
attrs: Mapping[str, str] | None = None,
classes: FormClasses | None = None,
id_prefix: str = "f",
describe: bool = True,
confirm: str | None = None,
) -> Widget
Generate and render a form for a Pydantic schema in one call.
Sugar over :func:~tempest_fastapi_sdk.ui.forms.form_spec_for
followed by :func:render_form. Reach for the two-step version when
you want to patch the generated specification before rendering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
type[BaseModel]
|
The schema describing the form. |
required |
action
|
str
|
The form |
required |
method
|
str
|
|
'post'
|
values
|
Mapping[str, Any] | None
|
Current values, overriding the schema defaults. |
None
|
errors
|
Mapping[str, Sequence[str]] | None
|
Per-field validation messages. |
None
|
include
|
Sequence[str]
|
Render only these fields, in order. |
()
|
exclude
|
Sequence[str]
|
Field names to drop. |
()
|
submit_label
|
str
|
Text of the submit button. |
'Enviar'
|
submit
|
bool
|
Whether to render the submit button. |
True
|
form_errors
|
Sequence[str]
|
Form-level messages. |
()
|
attrs
|
Mapping[str, str] | None
|
Extra attributes on the
|
None
|
classes
|
FormClasses | None
|
CSS class overrides. |
None
|
id_prefix
|
str
|
Prefix of the generated control ids. |
'f'
|
describe
|
bool
|
Whether a field |
True
|
confirm
|
str | None
|
Question asked before the form submits,
emitted as |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Widget |
Widget
|
The rendered |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the optional |
UnsupportedFieldError
|
When a field is a nested model or a
|
ValueError
|
When |
render_form
¶
render_form(spec: FormSpec) -> Widget
Render a whole form from its specification.
Messages of hidden fields join the form-level errors, prefixed
with the field label, because the field itself shows nothing. A form
holding a file field gets enctype="multipart/form-data"
unless :attr:FormSpec.attrs sets an enctype of its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
FormSpec
|
The form description. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Widget |
Widget
|
The |
Widget
|
every field, and the submit button when |
|
Widget
|
attr: |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the optional |
render_field
¶
Render one field: label, control, hint and messages.
A hidden field is the exception: it renders as the bare
<input type="hidden">, with no wrapper, label or hint. Its
messages have nowhere to show, so :func:render_form lists them with
the form-level errors instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
FormSpec
|
The owning form, read for class names and the id prefix. |
required |
field
|
FieldSpec
|
The field to render. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Widget |
Widget
|
The field wrapper, or the hidden input itself. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the optional |
fields_for
¶
fields_for(
schema: type[BaseModel],
*,
values: Mapping[str, Any] | None = None,
errors: Mapping[str, Sequence[str]] | None = None,
include: Sequence[str] = (),
exclude: Sequence[str] = (),
describe: bool = True,
) -> list[FieldSpec]
Derive the field specifications of a Pydantic schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
type[BaseModel]
|
The schema describing the form. |
required |
values
|
Mapping[str, Any] | None
|
Current values, overriding the
schema defaults. Accepts raw submitted strings (as returned
by :class: |
None
|
errors
|
Mapping[str, Sequence[str]] | None
|
Validation messages per field name, rendered under the matching control. |
None
|
include
|
Sequence[str]
|
When non-empty, render only these fields, in the given order. |
()
|
exclude
|
Sequence[str]
|
Field names to drop. |
()
|
describe
|
bool
|
Whether a field |
True
|
Returns:
| Type | Description |
|---|---|
list[FieldSpec]
|
list[FieldSpec]: One spec per rendered field, in schema |
list[FieldSpec]
|
declaration order (or |
Raises:
| Type | Description |
|---|---|
UnsupportedFieldError
|
When a field is a nested model or a
|
KeyError
|
When |
form_spec_for
¶
form_spec_for(
schema: type[BaseModel],
*,
action: str,
method: str = "post",
values: Mapping[str, Any] | None = None,
errors: Mapping[str, Sequence[str]] | None = None,
include: Sequence[str] = (),
exclude: Sequence[str] = (),
submit_label: str = "Enviar",
submit: bool = True,
form_errors: Sequence[str] = (),
attrs: Mapping[str, str] | None = None,
classes: FormClasses | None = None,
id_prefix: str = "f",
describe: bool = True,
) -> FormSpec
Build the full :class:FormSpec of a schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
type[BaseModel]
|
The schema describing the form. |
required |
action
|
str
|
The form |
required |
method
|
str
|
|
'post'
|
values
|
Mapping[str, Any] | None
|
Current values. |
None
|
errors
|
Mapping[str, Sequence[str]] | None
|
Per-field messages. |
None
|
include
|
Sequence[str]
|
Render only these fields, in order. |
()
|
exclude
|
Sequence[str]
|
Field names to drop. |
()
|
submit_label
|
str
|
Text of the submit button. |
'Enviar'
|
submit
|
bool
|
Whether to render the submit button. |
True
|
form_errors
|
Sequence[str]
|
Form-level messages. |
()
|
attrs
|
Mapping[str, str] | None
|
Extra attributes on the
|
None
|
classes
|
FormClasses | None
|
CSS class overrides. |
None
|
id_prefix
|
str
|
Prefix of the generated control ids. Give each form on the same page its own prefix. |
'f'
|
describe
|
bool
|
Whether field descriptions fill in the hint of
fields without a |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
FormSpec |
FormSpec
|
The form description, ready to render or to patch. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
UnsupportedFieldError
¶
Bases: ValueError
Raised when a schema field has no meaningful HTML control.
Nested models and bytes payloads are the two cases: a nested model
needs a form of its own, and a file upload is declared as FastAPI's
UploadFile rather than a value coerced from a string.
parse_form
async
¶
parse_form(
schema: type[T],
request: FormRequestLike,
*,
include: Sequence[str] = (),
exclude: Sequence[str] = (),
extra: Mapping[str, Any] | None = None,
error_message: Callable[[Mapping[str, Any]], str] | None = None,
) -> FormResult[T]
Read, coerce and validate a submitted form against a schema.
Only the schema's own fields are read from the body; anything else the browser sent (CSRF tokens, HTMX bookkeeping) is ignored, so a stray input cannot smuggle a value into the model.
A key the body does not carry at all is left out of the payload
rather than sent as None, so the schema's own default applies
and a required field reports Field required against itself.
Booleans are the exception: an unchecked checkbox submits nothing,
so an absent boolean key means False.
A file field (UploadFile, list[UploadFile], or a field whose
ui block forces {"control": "file"}) receives the uploaded
UploadFile objects themselves. An empty file control counts as an
absent key, and a file never goes back into
:attr:FormResult.values — a browser cannot pre-fill a file input,
so the re-rendered control comes back empty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
type[T]
|
The schema to validate against — the same one the form was generated from. |
required |
request
|
FormRequestLike
|
The incoming |
required |
include
|
Sequence[str]
|
When non-empty, read only these fields from the body. |
()
|
exclude
|
Sequence[str]
|
Field names never read from the body.
Use it for values the server owns (an owner id, a status)
and pass them through |
()
|
extra
|
Mapping[str, Any] | None
|
Server-side values merged in after the body, overriding anything submitted under the same name. |
None
|
error_message
|
Callable[[Mapping[str, Any]], str] | None
|
Maps
a raw Pydantic error dict to the message shown to the
reader. Defaults to Pydantic's own |
None
|
Returns:
| Type | Description |
|---|---|
FormResult[T]
|
FormResult[T]: The validated model, or the messages and raw |
FormResult[T]
|
values needed to re-render the form. |
Example
FormRequestLike
¶
Bases: Protocol
Any request exposing an awaitable form() returning a mapping.
Matches fastapi.Request and starlette.requests.Request as well
as lightweight test doubles.
FormResult
dataclass
¶
FormResult(
value: T | None = None,
errors: dict[str, list[str]] = dict(),
form_errors: list[str] = list(),
values: dict[str, Any] = dict(),
)
Bases: Generic[T]
The outcome of parsing a submitted form.
Attributes:
| Name | Type | Description |
|---|---|---|
value |
T | None
|
The validated model, or |
errors |
dict[str, list[str]]
|
Validation messages per field
name, ready to hand back to
:func: |
form_errors |
list[str]
|
Messages that belong to no single field (model-level validators). |
values |
dict[str, Any]
|
The raw submitted values, so a re-rendered form keeps what the reader typed. |
ok
property
¶
Whether the submission validated.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
collected. |
unwrap
¶
Return the validated model, or fail loudly.
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The validated model. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the submission did not validate. Check
:attr: |
form_dependency
¶
form_dependency(
schema: type[T],
*,
include: Sequence[str] = (),
exclude: Sequence[str] = (),
extra: Mapping[str, Any] | None = None,
error_message: Callable[[Mapping[str, Any]], str] | None = None,
) -> Callable[[Request], Awaitable[FormResult[T]]]
Build a FastAPI dependency that parses a form into a schema.
The dependency is :func:parse_form bound to schema and the
given options, taking the Request itself so the route does not
have to. It is a framework hook, not a wrapper: FastAPI injects the
Request into the returned callable and hands its result to the
route.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
type[T]
|
The schema to validate against. |
required |
include
|
Sequence[str]
|
Read only these fields from the body. |
()
|
exclude
|
Sequence[str]
|
Field names never read from the body. |
()
|
extra
|
Mapping[str, Any] | None
|
Fixed server-side values merged
in after the body. A value that depends on the request (the
current user) is not known when the dependency is built:
exclude the field, parse, and set it in the route — or call
:func: |
None
|
error_message
|
Callable[[Mapping[str, Any]], str] | None
|
Maps a raw Pydantic error dict to the message shown to the reader. |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[Request], Awaitable[FormResult[T]]]
|
Callable[[Request], Awaitable[FormResult[T]]]: The dependency, |
Callable[[Request], Awaitable[FormResult[T]]]
|
ready for |
Example
from typing import Annotated
from fastapi import Depends, FastAPI
from pydantic import BaseModel
from tempest_fastapi_sdk.ui.forms import FormResult, form_dependency
app: FastAPI = FastAPI()
class SignupSchema(BaseModel):
email: str
SignupForm = Annotated[
FormResult[SignupSchema],
Depends(form_dependency(SignupSchema)),
]
@app.post("/signup")
async def signup(result: SignupForm) -> dict[str, bool]:
return {"ok": result.ok}
FormSpec
dataclass
¶
FormSpec(
action: str,
fields: Sequence[FieldSpec],
method: Literal["post", "get"] = "post",
submit_label: str = "Enviar",
errors: Sequence[str] = (),
submit: bool = True,
attrs: Mapping[str, str] = dict(),
classes: FormClasses = FormClasses(),
id_prefix: str = "f",
)
A whole form: where it posts, what it holds, how it is labelled.
Attributes:
| Name | Type | Description |
|---|---|---|
action |
str
|
The |
fields |
Sequence[FieldSpec]
|
The fields, in render order. |
method |
Literal['post', 'get']
|
The HTTP method. |
submit_label |
str
|
Text of the submit button. |
errors |
Sequence[str]
|
Form-level messages, rendered above the fields. |
submit |
bool
|
Whether to render the submit button. Turn it off to place your own actions around the generated fields. |
attrs |
Mapping[str, str]
|
Extra attributes on the |
classes |
FormClasses
|
The CSS class names to apply. |
id_prefix |
str
|
Prefix of the generated control ids
( |
multipart
property
¶
Whether the form must be submitted as multipart/form-data.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
which is what makes |
|
bool
|
func: |
|
bool
|
|
field_named
¶
field_named(name: str) -> FieldSpec
Return one field by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The field name to look up. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
FieldSpec |
FieldSpec
|
The matching field. |
Raises:
| Type | Description |
|---|---|
KeyError
|
When no field carries that name. |
FieldSpec
dataclass
¶
FieldSpec(
name: str,
label: str,
control: Control = "input",
input_type: str = "text",
value: str = "",
selected_values: Sequence[str] = (),
options: Sequence[SelectOption] = (),
required: bool = False,
multiple: bool = False,
placeholder: str = "",
help_text: str = "",
errors: Sequence[str] = (),
autocomplete: str = "",
rows: int = 4,
accept: str = "",
constraints: Mapping[str, str] = dict(),
attrs: Mapping[str, str] = dict(),
)
Everything needed to render one form field.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The submitted field name, matching the schema field. |
label |
str
|
The |
control |
Control
|
Which HTML control to render. |
input_type |
str
|
The |
value |
str
|
The current single value, pre-filled into the control. |
selected_values |
Sequence[str]
|
Current values for a multiple select. Ignored by the other controls. |
options |
Sequence[SelectOption]
|
Options of a |
required |
bool
|
Whether the control renders |
multiple |
bool
|
Whether a |
placeholder |
str
|
Placeholder text for text-like controls. |
help_text |
str
|
Hint rendered under the control and wired to it
through |
errors |
Sequence[str]
|
Validation messages for this field. A
non-empty list also marks the control |
autocomplete |
str
|
The |
rows |
int
|
Row count for a |
accept |
str
|
The |
constraints |
Mapping[str, str]
|
Native validation attributes
derived from the schema — |
attrs |
Mapping[str, str]
|
Extra attributes merged into the control, last, so they win. |
SelectOption
dataclass
¶
One <option> of a <select> control.
Attributes:
| Name | Type | Description |
|---|---|---|
value |
str
|
The submitted value. |
label |
str
|
The text shown to the reader. |
selected |
bool
|
Whether the option renders as selected. |
FormClasses
dataclass
¶
FormClasses(
form: str = "tui-form",
errors: str = "tui-form__errors",
field: str = "tui-field",
field_invalid: str = "tui-field--invalid",
label: str = "tui-field__label",
control: str = "tui-field__control",
help_text: str = "tui-field__help",
error: str = "tui-field__error",
actions: str = "tui-form__actions",
submit: str = "tui-btn",
required_mark: str = "tui-field__required",
)
CSS class names used by the rendered form.
The defaults match the classes defined by
:data:tempest_fastapi_sdk.ui.forms.FORM_STYLESHEET, so including
that sheet styles a generated form with no further work. Override
them to plug the form into a design system of your own.
Attributes:
| Name | Type | Description |
|---|---|---|
form |
str
|
Class of the |
errors |
str
|
Class of the form-level error list. |
field |
str
|
Class of each field wrapper. |
field_invalid |
str
|
Extra class added to a wrapper holding an invalid field. |
label |
str
|
Class of each |
control |
str
|
Class of each input / select / textarea. |
help_text |
str
|
Class of the hint under a control. |
error |
str
|
Class of a field-level error message. |
actions |
str
|
Class of the wrapper holding the submit button. |
submit |
str
|
Class of the submit button. |
required_mark |
str
|
Class of the marker appended to a required field's label. |
form_stylesheet
¶
form_stylesheet(
*, classes: FormClasses | None = None, theme: ThemeTokens | None = None
) -> StyleSheet
Build the stylesheet that styles a generated form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
classes
|
FormClasses | None
|
The class names to target.
Defaults to the same names
:func: |
None
|
theme
|
ThemeTokens | None
|
The tokens whose custom properties
the rules reference. Only the prefix matters here — pass the
same theme your application sheet emits, or leave it at the
default |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
StyleSheet |
StyleSheet
|
The form rules, with no reset and no token block of |
StyleSheet
|
their own, ready to :meth: |
|
StyleSheet
|
application sheet. |