Dash Pydantic Form

0.18.3 · active · verified Sat Apr 11

Dash-pydantic-form is a Python library that enables rapid creation of interactive forms within Plotly Dash applications, powered by Pydantic models. It leverages dash-mantine-components (DMC) for a rich set of input fields and seamlessly handles complex data structures like nested models and lists. The library is actively maintained, with frequent minor and patch releases, and is currently at version 0.18.3.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a basic Dash application with a form generated directly from a Pydantic `BaseModel`. It includes the necessary imports, model definition, `ModelForm` instantiation in the layout, and a callback to capture and validate the submitted form data.

import os
from datetime import date
from typing import Literal

from dash import Dash, html, callback, Input, Output
from dash_pydantic_form import ModelForm
from pydantic import BaseModel, Field, ValidationError

# Define a Pydantic model
class Employee(BaseModel):
    first_name: str = Field(title="First name")
    last_name: str = Field(title="Last name")
    office: Literal["au", "uk", "us", "fr"] = Field(title="Office")
    joined: date = Field(title="Employment date")

# Initialize the Dash app
app = Dash(__name__)

# Define the app layout
app.layout = html.Div([
    html.H1("Employee Form"),
    ModelForm(
        Employee,
        aio_id="employees_form_id",
        form_id="new_employee_form"
    ),
    html.Div(id="form-output")
])

# Define a callback to process form data
@callback(
    Output("form-output", "children"),
    Input(ModelForm.ids.main("employees_form_id", "new_employee_form"), "data")
)
def use_form_data(form_data: dict):
    if form_data is None:
        return html.Pre("Waiting for form data...")
    try:
        employee = Employee(**form_data)
        return html.Pre(f"Validated Employee: {employee.model_dump_json(indent=2)}")
    except ValidationError as exc:
        return html.Pre(f"Validation Error:\n{exc.errors()}\nRaw Data: {form_data}", style={'color': 'red'})

if __name__ == '__main__':
    app.run(debug=True)

view raw JSON →