Repository navigation
Description
Goal
Build first-class form integration that can render Citry UI forms from Python form/schema classes and connect validation errors back to fields, while preserving the existing manual HTML form workflow.
The initial motivating question is Django integration: can a Django model or form be used with component State, and how should it be serialized? Component.State currently round-trips as strict JSON, so framework runtime objects should not be serialized directly. Form integration should instead map Python form/model metadata and validated values onto Citry's existing State, Events, and UI-field contracts.
Current layers
There are several layers to Form integration:
-
Render a UI form from a Python class — ❌ Not implemented yet.
Add support for generating a form from a Python class. Candidate sources include dataclasses, Pydantic, SQLModel, and Django form or model metadata. The mapping needs to cover types, constraints, defaults, descriptions, choices, names, IDs, labels, errors, and accessibility wiring.
-
Pre-fill a form with Python data — ✅ Implemented.
Write the form's HTML manually and connect data from State into individual fields (documentation). For example,
:c-querymeans “set the input's value toState.query”:<input type="search" placeholder="Search..." :c-query />
-
Send form data to the server — ✅ Implemented.
Put
@c-submiton a<form>to send its data to the server. Here,@c-submit.prevent="save"means “on the browser's submit event, send the form data to the component event handler namedsave”:<form @c-submit.prevent="save"> <label> Work email <input name="email" type="email" autocomplete="email" required /> </label> ... </form>
-
Client-side validation — ❌ Not implemented.
Today, applications must write client-side validation logic manually. Define how generated and manual forms expose constraints, validation timing, field/form errors, and accessible invalid states in the browser.
-
Server-side validation — ❌ Not implemented.
Define how submitted fields are parsed into typed values, how Python/Django validation runs, and how field and non-field errors map back to the correct Citry UI controls.
Design requirements
- Normalize dataclass, Pydantic, SQLModel, and Django form or model metadata behind one form description contract.
- Generate Citry UI fields from types, constraints, defaults, descriptions, and choices.
- Parse submissions into typed values and route validation failures back to the correct fields.
- Support per-field overrides through ordinary component composition and slots.
- Preserve manual-form escape hatches; the already-supported State bindings and
@c-submitflow remain useful independently. - Keep rich Django Form/Model instances out of serialized State. Store JSON-safe values or model identifiers and rebuild/reload framework objects on the server.
- Audit the bounded Pydantic gaps: aliases and form metadata, automatic mapping of existing Events field errors into Citry UI fields, and packaged result serialization.
Citry already supports Pydantic v1 and v2 component schemas, validation, introspection, Events schemas, and OpenAPI generation. This work should build on those contracts.
Activity
JuroOravec commentedon Oct 25, 2026
Parked for now. Forms deserve their own hands-on exploration, so that they feel smooth and easy to use, are easy to customize, and are flexible enough to replace Django forms. This is the first design pass, kept here as a starting point, not a decision. (
model_basebelow is the #172 setting.)What exists today
:c-fieldbinds a control to State, and@c-submitsends form data to a handler.validated per field, by Citry's coercion or by Pydantic (
ext/events/schemas.py,_validate_pydantic,about line 400). Each failure is recorded under its dotted field path.
EventErroralready carries afieldErrorsmap to the browser (ext/events/errors.py)._schema_introspection.pyreads dataclass, Pydantic v1 and v2, andNamedTuple fields into one internal
_RawFieldshape.CForm,CField(label, description and error slots,invalid,required,control_id), plus the input, select, number, date, time, file, multi-select andcollection components.
What is missing is the shared description of a form, the generation from it, mapping
fieldErrorsonto fields automatically, and browser-side constraints.
Decision summary: three phases, smallest valuable first
constraints derived from the schema, for forms written by hand. This is small and useful on its own.
citry.forms.FormSpec, built from a dataclass,a Pydantic model (which covers SQLModel), a Django
Formor a DjangoModelForm.<c-CAutoForm>in Citry UI renders aFormSpec, with per-fieldoverrides through slots.
Phase A: field errors and constraints on hand-written forms
CFieldgainsfor_error="email", a dotted path. With@c-submiton the surroundingCForm, thefield shows
fieldErrors[path]from the last call's error.aria-invalidand links the message witharia-describedby, in the browser, without aserver round trip.
__all__, or anEventErrorwithoutfieldErrors) show inCForm's error area.constraints_for(schema, "email")returns the native attributes for afield:
required,minlength,maxlength,min,max,step,pattern, andtype(email,url,number,date). The author spreads them withc-bind, so the browser checks beforesending. The server stays the authority and validates again.
EventError.from_django_form(form)buildsfieldErrorsfromform.errors, putting__all__under the form-level key.Phase B:
FormSpecFormSpec(fields=[FieldSpec(...)]). EachFieldSpechasname(the submitted name;the validation alias when one exists),
path,kind(text, email, url, integer, decimal, boolean,date, time, datetime, choice, multi_choice, file, nested),
required,default,label,description,choices,constraints, andwidget(an optional hint).Annotatedmarker,citry.forms.FormField(label=..., description=..., widget=...), that works the same on dataclassand Pydantic fields. Pydantic's own
titleanddescriptionare read too. So are Django'slabel,help_textandchoices.FormSpec.from_schema(cls)for a dataclass or Pydantic model, through_schema_introspection.It accepts a
model_basemodel or a generated dataclass from Pydantic: optional automatic models and a project-wide default schema base class #172 alike, so the two features donot depend on each other.
FormSpec.from_django_form(FormClass).ModelChoiceFieldchoices are read on the server atrender time. They are not stored.
Formand model instances never enter State. Stateholds the cleaned primitive values, or a model's primary key, and the handler rebuilds the Django
object on the server.
Phase C:
<c-CAutoForm>Usage:
<c-CAutoForm c-spec="spec" event="save" />renders aCFormwith oneCFieldperfield, and wires phase A's error mapping and constraints automatically.
Control choice:
EmailStror email kindLiteral,Enumor choicesUploadedFilePer-field override:
<c-fill name="field:email" data="f">. The slot data carries theFieldSpec, the control id, the current value and the current error, so a custom control keeps thewiring.
Submission: to the named handler, whose data class should be the schema the form was built
from. Validation is then the handler's existing data validation, with no second rule set.
Error modes
dict[str, X], an arbitrary class)field:<name>override.ValueErrorwhen theFormSpecis built, naming both fields.fieldErrors.CFormCollection.for_errornames a path the handler never reportscitry checkwarning when the handler's data class is known. At runtime the field simply shows no error.@c-submitalready sends files asUploadedFile. The spec marks the form multipart.Alternatives considered
model_json_schema()) as the form contract. It loses Python typesand Django metadata, and it describes validation, not UI. It can still be emitted from a
FormSpeclater, for client libraries.
and it is accessible by default. Custom validators would duplicate server rules in a second
language.
prerequisite for C anyway.
What would show this design is wrong
CAutoFormsaves little. Then phase A plusFormSpec, kept as data for authors to iterate in their own templates, is the right stopping point.ModelFormbehaviour (bound instances, unique checks,save()) does not fit validation inan Events handler. Then the Django adapter should run the real
ModelForminside the handler, anduse
FormSpeconly for rendering.