AutoForm¶
Generate a labelled form from a typed FormModel and optionally submit it through HTMX.
| Import | from hedron import AutoForm |
| Distribution | hedron |
| Backend activity | On submit |
| Normal render mode | RenderMode.FRAGMENT |
Live demo¶
Docs simulation — not a running Hedron server. Interactive demos show a “Simulated HTMX” trace when applicable.
Minimal runnable app.py that reproduces this demo (real Hedron, not the docs simulator):
from __future__ import annotations
import json
import os
from fastapi import Request
from pydantic import ValidationError
from hedron import (
Field,
Form,
FormErrors,
FormField,
FormModel,
Hedron,
InteractionResult,
Page,
Stack,
SubmitButton,
Text,
TextInput,
html,
)
from hedron.security import csrf_token_for_request
app = Hedron(
title="Form demo",
security="standard",
explorer="off",
session_secret=os.environ.get("HEDRON_SESSION_SECRET", "dev-only"),
)
region = app.region("demo-form")
class Invite(FormModel):
email: str = Field(min_length=3, label="Email address")
def _csrf(request: Request) -> str:
return csrf_token_for_request(request, request.app.state.hedron_security)
def form_body(*, csrf_token: str, errors: tuple[str, ...] = ()):
return html.div(
Form(
FormErrors(errors),
html.input(type="hidden", name="csrf_token", value=csrf_token),
FormField(
name="email",
label="Email address",
control=TextInput(name="email", placeholder="ada@example.com"),
),
SubmitButton("Submit"),
**{
"hx-post": "/demo",
"hx-target": region.selector,
"hx-swap": "outerHTML",
"hx-headers": json.dumps({"X-CSRF-Token": csrf_token}),
},
),
id=region.id,
)
@app.page("/")
def home(request: Request) -> Page:
return Page(Stack(form_body(csrf_token=_csrf(request))), title="Form")
@app.component("/demo", methods=["POST"], fragment_regions=(region,))
async def submit(request: Request) -> InteractionResult:
form = await request.form()
try:
data = Invite.model_validate({"email": form.get("email", "")})
except ValidationError:
return InteractionResult(
content=form_body(
csrf_token=_csrf(request),
errors=("Enter a valid work email.",),
),
status_code=422,
region_id=region.id,
)
return InteractionResult(
content=html.div(
html.strong("Submitted"),
Text(f"Queued for {data.email}."),
id=region.id,
role="status",
),
region_id=region.id,
)
Basic use¶
from hedron import AutoForm
component = AutoForm(InviteMember, action='/invite', csrf_token=csrf_token, submit_label='Send invite')
Compose under Page for full documents, or return from a fragment route for HTMX swaps.
How it works¶
AutoForm derives field labels and required state from model metadata, adds error and CSRF nodes, and uses normal form submission as its baseline. Obtain csrf_token with csrf_token_for_request(request, policy) after a safe GET. For HTMX-targeted POSTs, prefer the explicit Form loop in the forms and actions guide.
This component can initiate or represent a backend interaction. The live documentation intercepts that interaction with JavaScript and shows the same pending, success, or replacement states without making a real request. In an application, keep the URL, authorization, validation, and returned fragment on the server; JavaScript is only progressive enhancement.
Constructor and parameters¶
AutoForm(model, *, action, method='post', csrf_token=None, values=None, errors=(), submit_label='Submit', target=None)
| Parameter | Type | Meaning |
|---|---|---|
model |
type[FormModel] | FormModel |
Field schema or populated instance. |
action |
SafeUrl | str |
Validated endpoint. |
method |
str |
GET or POST behavior. |
csrf_token |
str | None |
Hidden CSRF value from csrf_token_for_request; required for POST. |
values |
Mapping |
Values restored after validation. |
errors |
Sequence[str] |
Form-level errors. |
submit_label |
str |
Primary action label. |
target |
safe CSS selector | None |
HTMX response target (prefer explicit Form composition when using hx-target). |
Composition and backend behavior¶
Keep AutoForm at the smallest semantic boundary. Fragment routes should return only
the replaced region and preserve stable target IDs across success, validation, empty,
loading, and error responses.
Mutating flows must use POST, validate CSRF, authorize on the server, re-validate typed input, and return a bounded fragment. GET remains safe and repeatable; native submit should still work without HTMX.
Accessibility¶
Review generated labels and add model titles that make domain-specific fields understandable.
Security¶
Escaping and SafeUrl / TrustedHtml are framework concerns; authorization and data
exposure remain application code. Redact secrets before rendering.
Common mistakes¶
- Generation does not replace authorization, CSRF validation, or server-side model validation. Do not leave
csrf_tokenundefined. - Do not copy docs-preview JavaScript into an application server.