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.)
            • 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

    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.2.0.tar.gz (17.4 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.2.0-py3-none-any.whl (10.9 kB view details)

    Uploaded Python 3

    File details

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

    File metadata

    • Download URL: pydantic_to_html-0.2.0.tar.gz
    • Upload date:
    • Size: 17.4 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.2.0.tar.gz
    Algorithm Hash digest
    SHA256 40db64421ae81e86fdf7beed8b83abd3159ebd7c67c71699be0a945d4fe709e6
    MD5 49f5410e9ed398eadcc48f43d4d02c98
    BLAKE2b-256 d483f4e08a7833e76298a952ebe5c58b6470abbede86f11ea82d9fcd4b152646

    See more details on using hashes here.

    File details

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

    File metadata

    File hashes

    Hashes for pydantic_to_html-0.2.0-py3-none-any.whl
    Algorithm Hash digest
    SHA256 f7359b10c734bde9a4d56e633c9b4746e73957e8b39bf460b66f0520ede5b0b2
    MD5 118dc2044f354a848956b2dbf5abac11
    BLAKE2b-256 ddd4cf3b5d16452f42892817b7d2f0c4ae935ed7c6982767f859f07dee9239a0

    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