Skip to content

Form integration: generate UI and validation from Python classes #129

Open

Description

@JuroOravec

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:

  1. 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.

  2. 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-query means “set the input's value to State.query”:

    <input
      type="search"
      placeholder="Search..."
      :c-query
    />
  3. Send form data to the server — ✅ Implemented.

    Put @c-submit on 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 named save”:

    <form @c-submit.prevent="save">
      <label>
        Work email
        <input
          name="email"
          type="email"
          autocomplete="email"
          required
        />
      </label>
      ...
    </form>
  4. 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.

  5. 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-submit flow 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

  1. JuroOravec commented on Oct 25, 2026

    @JuroOravec
    MemberAuthor

    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_base below is the #172 setting.)

    What exists today

    • Pre-fill and submit (layers 2 and 3) work: :c-field binds a control to State, and
      @c-submit sends form data to a handler.
    • Server-side validation of submitted data is partly there. A handler's data class is already
      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. EventError already carries a
      fieldErrors map to the browser (ext/events/errors.py).
    • Field metadata exists: _schema_introspection.py reads dataclass, Pydantic v1 and v2, and
      NamedTuple fields into one internal _RawField shape.
    • Citry UI has the controls: CForm, CField (label, description and error slots, invalid,
      required, control_id), plus the input, select, number, date, time, file, multi-select and
      collection components.

    What is missing is the shared description of a form, the generation from it, mapping fieldErrors
    onto fields automatically, and browser-side constraints.

    Decision summary: three phases, smallest valuable first

    1. Phase A: connect what exists. Field errors flow back to fields, and controls carry the HTML
      constraints derived from the schema, for forms written by hand. This is small and useful on its own.
    2. Phase B: one form description plus adapters. citry.forms.FormSpec, built from a dataclass,
      a Pydantic model (which covers SQLModel), a Django Form or a Django ModelForm.
    3. Phase C: a generated form. <c-CAutoForm> in Citry UI renders a FormSpec, with per-field
      overrides through slots.

    Phase A: field errors and constraints on hand-written forms

    • Error mapping:
      • CField gains for_error="email", a dotted path. With @c-submit on the surrounding CForm, the
        field shows fieldErrors[path] from the last call's error.
      • It sets aria-invalid and links the message with aria-describedby, in the browser, without a
        server round trip.
      • Errors with no field (Django's __all__, or an EventError without fieldErrors) show in
        CForm's error area.
    • Constraints: a helper constraints_for(schema, "email") returns the native attributes for a
      field: required, minlength, maxlength, min, max, step, pattern, and type (email,
      url, number, date). The author spreads them with c-bind, so the browser checks before
      sending. The server stays the authority and validates again.
    • Django: EventError.from_django_form(form) builds fieldErrors from form.errors, putting
      __all__ under the form-level key.

    Phase B: FormSpec

    • Shape: FormSpec(fields=[FieldSpec(...)]). Each FieldSpec has name (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, and widget (an optional hint).
    • Metadata from the author: an Annotated marker,
      citry.forms.FormField(label=..., description=..., widget=...), that works the same on dataclass
      and Pydantic fields. Pydantic's own title and description are read too. So are Django's
      label, help_text and choices.
    • Adapters:
    • State stays strict JSON. Rich Django Form and model instances never enter State. State
      holds 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 a CForm with one CField per
      field, and wires phase A's error mapping and constraints automatically.

    • Control choice:

      Field kind Control
      str text input
      EmailStr or email kind email input
      bool checkbox
      Literal, Enum or choices select
      int, float or Decimal number input
      date or time date input or time input
      list of choices multi-select
      UploadedFile file input
      nested model a fieldset with dotted names
    • Per-field override: <c-fill name="field:email" data="f">. The slot data carries the
      FieldSpec, the control id, the current value and the current error, so a custom control keeps the
      wiring.

    • 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

    Situation Result
    A field annotation with no generated control (dict[str, X], an arbitrary class) Fails when the form renders, naming the field, and says to give it a field:<name> override.
    Two fields map to the same submitted name (an alias collides with another field) ValueError when the FormSpec is built, naming both fields.
    A constraint HTML cannot express (a custom validator, a cross-field rule) Checked only on the server. The docs say so. Its error still reaches the field through fieldErrors.
    A list of nested models Not generated in this version. Raises with a pointer to CFormCollection.
    for_error names a path the handler never reports citry check warning when the handler's data class is known. At runtime the field simply shows no error.
    A Django form with file fields It works: @c-submit already sends files as UploadedFile. The spec marks the form multipart.

    Alternatives considered

    • Use JSON Schema (Pydantic's model_json_schema()) as the form contract. It loses Python types
      and Django metadata, and it describes validation, not UI. It can still be emitted from a FormSpec
      later, for client libraries.
    • Generate custom JavaScript validators. Native constraint validation covers the common rules,
      and it is accessible by default. Custom validators would duplicate server rules in a second
      language.
    • Do phase C first. Rejected: phase A is useful for every hand-written form today and is a
      prerequisite for C anyway.

    What would show this design is wrong

    • Most real forms override nearly every field, so CAutoForm saves little. Then phase A plus
      FormSpec, kept as data for authors to iterate in their own templates, is the right stopping point.
    • Django ModelForm behaviour (bound instances, unique checks, save()) does not fit validation in
      an Events handler. Then the Django adapter should run the real ModelForm inside the handler, and
      use FormSpec only for rendering.
  2. added
    next-sprint
    on Oct 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    next-sprint

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions