Skip to main content

A library to convert Pydantic models to HTML

Project description

pydantic-to-html

A Python library that automatically converts Pydantic models into structured HTML using safe and semantic defaults.

Overview

pydantic-to-html infers an appropriate HTML structure based on the types of fields in a Pydantic model, including support for nested models, lists, and forms for user input.

Installation

pip install pydantic-to-html

Usage

from pydantic import BaseModel
from pydantic_to_html import render_html

class User(BaseModel):
    name: str
    email: str
    age: int

user = User(name="John Doe", email="john@example.com", age=30)
html = render_html(user)
print(html)

Features

  • ✅ Automatic HTML Conversion – Converts any Pydantic model into a structured HTML representation.
  • ✅ Recursive Nesting – Handles nested models and lists of models gracefully.
  • ✅ Table-Based Rendering – Uses elements for structured data representation.
  • ✅ List Support – Renders lists as
      or
        , depending on the data type.
      1. ✅ Automatic Form Generation – Can generate editable forms with elements.
      2. ✅ Type-Safe Defaults – Uses appropriate form fields based on the Pydantic field type (str, int, bool, datetime, etc.).
      3. ✅ Customizable Themes – Allows passing custom CSS classes or styles.
      4. ✅ HTMX Support – Optionally integrates HTMX for live updates.
      5. ✅ Validation & Constraints – Uses Pydantic field constraints to enforce validation on form inputs.

    API

    def render_html(
        model: BaseModel,
        editable: bool = False,
        theme: str | None = None,
        htmx: bool = False,
        htmx_mode: str = "full",  # "full" | "inline" | "none"
        max_depth: int | None = None,
    ) -> str:
        """Converts a Pydantic model into HTML (table or form)."""
    

    Type Mapping

  • Pydantic Type Default HTML Element
    str
    int
    float
    bool
    datetime
    List[str] Multiple inside
      List[Model] Nested
      Dict[str, Any] Table (if structured), <ul> otherwise
      Enum Radio buttons
      Literal["A", "B"] Dropdown (<select>)

      HTMX Modes

      Mode Behavior
      "none" Static HTML
      "inline" updates on hx-trigger="change"
      "full" Whole form auto-submits on change

      Handling Nested Models & Lists

      • Lists of Primitives (List[str]) →
          with
        • elements.
        • Lists of Models (List[Model]) → Rendered as nested tables.
        • Dictionaries (Dict[str, Any]) → Rendered as a key-value table if structured, or
            if unstructured.
          • Nested Pydantic Models → Recursively rendered as nested tables, with a configurable max_depth to limit depth.

          Validation & Constraints Mapping

          • Min/Max Length (Field(min_length=3, max_length=50)) → minlength="3" maxlength="50"
          • Greater Than (Field(gt=0)) → min="0"
          • Regex Constraints (Field(regex="^[a-z]+$") → pattern="^[a-z]+$"

          Error Handling for Edge Cases

          • Unsupported Types (bytes, UUID, Callable)
            • UUID → Rendered as str(uuid)
            • bytes → Rendered as "[binary data]"
            • Callable → Rendered as "[function]"
          • Default Factories (Field(default_factory=...)) → Rendered appropriately with their defaults.

          Roadmap

          This is our current development roadmap. Contributions are welcome!

          Phase 1: Basic Rendering

          • Convert flat Pydantic models into tables
          • Support nested models using recursion
          • Support lists as
              elements

            Phase 2: Editable Forms

            • Render models as forms with fields
            • Infer input types from field types
            • Handle lists as multiple input fields

            Phase 3: Advanced Features

            • Add HTMX integration for interactive forms
            • Implement theme support
            • Add validation based on Pydantic constraints
            • Support for complex types (Enum, Literal, etc.)
            • Add custom rendering hooks

            Phase 4: Optimization & Extras

            • Performance improvements for large models
            • Add support for custom widgets
            • Implement max_depth control for nested models
            • Add accessibility features
            • Comprehensive documentation site

            License

            MIT

    Project details


    Download files

    Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

    Source Distribution

    pydantic_to_html-0.1.0.tar.gz (13.9 kB view details)

    Uploaded Source

    Built Distribution

    If you're not sure about the file name format, learn more about wheel file names.

    pydantic_to_html-0.1.0-py3-none-any.whl (10.0 kB view details)

    Uploaded Python 3

    File details

    Details for the file pydantic_to_html-0.1.0.tar.gz.

    File metadata

    • Download URL: pydantic_to_html-0.1.0.tar.gz
    • Upload date:
    • Size: 13.9 kB
    • Tags: Source
    • Uploaded using Trusted Publishing? No
    • Uploaded via: twine/6.1.0 CPython/3.12.6

    File hashes

    Hashes for pydantic_to_html-0.1.0.tar.gz
    Algorithm Hash digest
    SHA256 b7e3dc4668bfbf57de0a021745e8a9b5ed7f853952525bfca5c2de9ffb2c30d8
    MD5 9a2f02f9fafdaf498ff2869c1494af73
    BLAKE2b-256 a70af0dd03b90f250ac22e8fc0e69d4de27876368d5fc35cb4ddaafe0f277bb1

    See more details on using hashes here.

    File details

    Details for the file pydantic_to_html-0.1.0-py3-none-any.whl.

    File metadata

    File hashes

    Hashes for pydantic_to_html-0.1.0-py3-none-any.whl
    Algorithm Hash digest
    SHA256 b72ab241ef2c740ad3911225b5c68b2a70eb868c735702b9c6554ecef11a46f0
    MD5 56d9a5128f4f1d1344b45e8619720395
    BLAKE2b-256 4e85fe1acce9b4fc5fdba7a98caaac27f3e004006bdd901291b66997067ead4e

    See more details on using hashes here.

    Supported by

    AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page