Skip to main content

Create Dash forms from pydantic objects

Project description

Dash pydantic form

This package allows users to quickly create forms with Plotly Dash based on pydantic models.

See the full docs at dash-pydantic-form docs.

Check out a full self-standing example app in usage.py.

Getting started

Install with pip

pip install dash-pydantic-form

Create a pydantic model you would like to display a form for.

Note: This package uses pydantic 2.

from datetime import date
from typing import Literal
from pydantic import BaseModel, Field

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")

Then you can get an auto-generated form with ModelForm, leveraging dash-mantine-components (version 0.14) for form inputs.

from dash_pydantic_form import ModelForm

# somewhere in your layout:
form = ModelForm(
    Employee,
    aio_id="employees",
    form_id="new_employee",
)

Simple form

You can also render a pre-filled form by passing an instance of the data model rather than the class

# NOTE: This could come from a database
bob = Employee(first_name="Bob", last_name="K", office="au", joined="2020-05-20")

form = ModelForm(
    bob,
    aio_id="employees",
    form_id="bob",
)

You can then retrieve the contents of the whole form at once in a callback as follows

from dash import Input, Output, callback

@callback(
    Output("some-output-id", "some-output-attribute"),
    Input(ModelForm.ids.main("employees", "new_employee"), "data"),
)
def use_form_data(form_data: dict):
    try:
        print(Employee(**form_data))
    except ValidationError as exc:
        print("Could not validate form data:")
        print(exc.errors())
    return # ...

Customising inputs

The ModelForm will automaticlly pick which input type to use based on the type annotation for the model field. However, you can customise how each field input is rendered, and or pass additional props to the DMC component.

from dash_pydantic_form import ModelfForm, fields

form = ModelForm(
    Employee,
    aio_id="employees",
    form_id="new_employee",
    fields_repr={
        # Change the default from a Select to Radio items
        # NOTE: `description` can be set on pydantic fields as well
        "office": fields.RadioItems(description="Wich country office?"),
        # Pass additional props to the default input field
        "joined": {"maxDate": "2024-01-01"},
    },
)

You can also customise inputs by adding arguments to the fields' json_schema_extra if you don't mind mixing data and presentation layers.

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",
        description="Wich country office?",
        # Use repr_type to change the default field used
        json_schema_extra={"repr_type": "RadioItems"},
    )
    joined: date = Field(
        title="Employment date",
        # Use repr_kwargs to pass default keyword arguments to the field
        json_schema_extra={"repr_kwargs": {"maxDate": "2024-01-01"}},
    )

form = ModelForm(Employee, aio_id="employees", form_id="new_employee")

Note: You can currently skip the json_schema_extra=... and just pass repr_type=..., repr_kwargs=... in the field. However, the **extras keyword arguments are deprecated on pydantic's Field so using json_schema_extra is more future-proof.

List of current field inputs:

Based on DMC:

  • Checkbox
  • Checklist
  • Color
  • Date
  • Json
  • Month
  • MultiSelect
  • Number
  • Password
  • RadioItems
  • Range
  • Rating
  • SegmentedControl
  • Select
  • Slider
  • Switch
  • Tags
  • Textarea
  • Text
  • Time
  • Year

Custom:

  • Dict
  • Table
  • List
  • Markdown
  • Model
  • Path
  • Quantity
  • TransferList

Creating sections

There are 2 main avenues to create form sections:

1. Create a submodel in one of the model fields

class HRData(BaseModel):
    office: Literal["au", "uk", "us", "fr"] = Field(title="Office")
    joined: date = Field(title="Employment date")

class EmployeeNested(BaseModel):
    first_name: str = Field(title="First name")
    last_name: str = Field(title="Last name")
    hr_data: HRData = Field(title="HR data")

ModelForm will then recognise HRData as a pydantic model and use the fields.Model to render it, de facto creating a section.

Nested model

2. Pass sections information to ModelForm

from dash_pydantic_form import FormSection, ModelForm, Sections

form = ModelForm(
    Employee,
    aio_id="employees",
    form_id="new_employee",
    sections=Sections(
        sections=[
            FormSection(name="General", fields=["first_name", "last_name"], default_open=True),
            FormSection(name="HR data", fields=["office", "joined"], default_open=False),
        ],
        # 3 render values are available: accordion, tabs and steps
        render="tabs",
    ),
)

Form sections

List of nested models

Dash pydantic form also handles lists of nested models with the possibility to add/remove items from the list and edit each one.

Let's say we now want to record the employee's pets

1. List

This creates a list of sub-forms each of which can take similar arguments as a ModelForm (fields_repr, sections).

class Pet(BaseModel):
    name: str = Field(title="Name")
    species: Literal["cat", "dog"] = Field(title="Species")
    age: int = Field(title="Age")

class Employee(BaseModel):
    first_name: str = Field(title="First name")
    last_name: str = Field(title="Last name")
    pets: list[Pet] = Field(title="Pets", default_factory=list)

form = ModelForm(
    Employee,
    aio_id="employees",
    form_id="new_employee",
    fields_repr={
        "pets": fields.List(
            fields_repr={
                "species": {"options_labels": {"cat": "Cat", "dog": "Dog"}}
            },
            # 3 render_type options: accordion, list or modal
            render_type="accordion",
        )
    },
)

List

2. Table

You can also represent the list of sub-models as an ag-grid table with fields.Table.

form = ModelForm(
    Employee,
    aio_id="employees",
    form_id="new_employee",
    fields_repr={
        "pets": fields.Table(
            fields_repr={
                "species": {"options_labels": {"cat": "Cat", "dog": "Dog"}}
            },
        )
    },
)

Table

Make fields conditionnally visible

You can make field visibility depend on the value of other fields in the form. To do so, simply pass a visible argument to the field.

class Employee(BaseModel):
    first_name: str
    last_name: str
    only_bob: str | None = Field(
        title="Only for Bobs",
        description="What's your favourite thing about being a Bob?",
        default=None,
    )

form = ModelForm(
    Employee,
    aio_id="employees",
    form_id="new_employee",
    fields_repr={
        "only_bob": fields.Textarea(
            visible=("first_name", "==", "Bob"),
        )
    },
)

Conditionally visible field

visible accepts a boolean, a 3-tuple or list of 3-tuples with format: (field, operator, value). The available operators are:

  • "=="
  • "!="
  • "in"
  • "not in"
  • "array_contains"
  • "array_contains_any"

NOTE: The field in the 3-tuples is a ":" separated path relative to the current field's level of nesting. If you need to reference a field from a parent or the root use the special values _parent_ or _root_.

E.g., visible=("_root_:first_name", "==", "Bob")

Discriminated unions

Dash pydantic form supports Pydantic discriminated unions with str discriminator

class HomeOffice(BaseModel):
    """Home office model."""

    type: Literal["home_office"]
    has_workstation: bool = Field(title="Has workstation", description="Does the employee have a suitable workstation")


class WorkOffice(BaseModel):
    """Work office model."""

    type: Literal["work_office"]
    commute_time: int = Field(title="Commute time", description="Commute time in minutes", ge=0)

class Employee(BaseModel):
    name: str = Field(title="Name")
    work_location: HomeOffice | WorkOffice | None = Field("Work location", default=None, discriminator="type")

form = ModelForm(
    Employee,
    aio_id="employees",
    form_id="new_employee",
    fields_repr={
        "work_location": {
            "fields_repr": {
                "type": fields.RadioItems(
                    options_labels={"home_office": "Home", "work_office": "Work"}
                )
            },
        },
    }
)

Discriminated union

Creating custom fields

To be written

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

dash_pydantic_form-0.9.0.tar.gz (63.7 kB view details)

Uploaded Source

Built Distribution

dash_pydantic_form-0.9.0-py3-none-any.whl (66.2 kB view details)

Uploaded Python 3

File details

Details for the file dash_pydantic_form-0.9.0.tar.gz.

File metadata

  • Download URL: dash_pydantic_form-0.9.0.tar.gz
  • Upload date:
  • Size: 63.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for dash_pydantic_form-0.9.0.tar.gz
Algorithm Hash digest
SHA256 499b02f3c8ba25470a3cb266dd8d47331652b78835fe8bacc2d50cf8a9e22e7a
MD5 b107258bbe9176022dc84e19f7d3f7c9
BLAKE2b-256 76f797be627415ebb628d761f7801ffb936291dcb10c3b63d2eca5412b2a06fd

See more details on using hashes here.

File details

Details for the file dash_pydantic_form-0.9.0-py3-none-any.whl.

File metadata

File hashes

Hashes for dash_pydantic_form-0.9.0-py3-none-any.whl
Algorithm Hash digest
SHA256 87a2446eb898676ae9e8decff6211757329aee25704efc16ba988268a43e9ac5
MD5 ebbd23955d84a69af63bde5fa31507c2
BLAKE2b-256 53a35c49434e9de91be0f4eaa0003473233cd94ff6fbd6fe8c0dfcb83556b34c

See more details on using hashes here.

Supported by

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