Skip to main content

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.)
            • Build and publish package to PyPI

            Phase 4: Future Enhancements

            • Add custom rendering hooks
            • Performance improvements for large models
            • Add support for custom widgets
            • Add support for Pydantic dataclasses
            • Add accessibility features
            • Create comprehensive documentation site

            Installation

            The package is available on PyPI:

            pip install pydantic-to-html
            

            License

            MIT

    Release files for pydantic-to-html 0.2.0

    For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

    Source distribution (sdist)

    Source distribution for pydantic-to-html 0.2.0
    File Size Uploaded
    pydantic_to_html-0.2.0.tar.gz 17.4 kB Details

    Built distribution (wheel)

    Table of built distributions (wheels) for pydantic-to-html 0.2.0
    File Interpreter ABI Platform
    pydantic_to_html-0.2.0-py3-none-any.whl Python 3 none any Details

    Total release size: 28.3 kB

    Release files / pydantic_to_html-0.2.0.tar.gz

    Download URL pydantic_to_html-0.2.0.tar.gz
    Size 17.4 kB
    Tags Source
    SHA-256 checksum
    How to use checksums
    40db64421ae81e86fdf7beed8b83abd3159ebd7c67c71699be0a945d4fe709e6
    BLAKE2b-256 checksum
    How to use checksums
    d483f4e08a7833e76298a952ebe5c58b6470abbede86f11ea82d9fcd4b152646
    Upload date
    Uploaded using Trusted Publishing?
    What is trusted publishing?
    No
    Uploaded via twine/6.1.0 CPython/3.12.6

    Release files / pydantic_to_html-0.2.0-py3-none-any.whl

    Download URL pydantic_to_html-0.2.0-py3-none-any.whl
    Size 10.9 kB
    Tags Python 3
    SHA-256 checksum
    How to use checksums
    f7359b10c734bde9a4d56e633c9b4746e73957e8b39bf460b66f0520ede5b0b2
    BLAKE2b-256 checksum
    How to use checksums
    ddd4cf3b5d16452f42892817b7d2f0c4ae935ed7c6982767f859f07dee9239a0
    Upload date
    Uploaded using Trusted Publishing?
    What is trusted publishing?
    No
    Uploaded via twine/6.1.0 CPython/3.12.6

    Release history Release notifications | RSS feed

    This release

    0.2.0 This release

    2 release files

    0.1.1

    2 release files

    0.1.0

    2 release files

    Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page