Giter Club home page Giter Club logo

streamlit-pydantic's Introduction

Streamlit Pydantic

Auto-generate Streamlit UI elements from Pydantic models.

Getting Started โ€ข Documentation โ€ข Support โ€ข Report a Bug โ€ข Contribution โ€ข Changelog

Streamlit-pydantic makes it easy to auto-generate UI elements from Pydantic models or dataclasses. Just define your data model and turn it into a full-fledged UI form. It supports data validation, nested models, and field limitations. Streamlit-pydantic can be easily integrated into any Streamlit app.

Beta Version: Only suggested for experimental usage.


Try out and explore various examples in our playground here.


Highlights

  • ๐Ÿช„ย  Auto-generated UI elements from Pydantic models & Dataclasses.
  • ๐Ÿ“‡ย  Out-of-the-box data validation.
  • ๐Ÿ“‘ย  Supports nested Pydantic models.
  • ๐Ÿ“ย  Supports field limits and customizations.
  • ๐ŸŽˆย  Easy to integrate into any Streamlit app.

Getting Started

Installation

Requirements: Python 3.6+.

pip install streamlit-pydantic

Usage

  1. Create a script (my_script.py) with a Pydantic model and render it via pydantic_form:

    import streamlit as st
    from pydantic import BaseModel
    import streamlit_pydantic as sp
    
    class ExampleModel(BaseModel):
        some_text: str
        some_number: int
        some_boolean: bool
    
    data = sp.pydantic_form(key="my_form", model=ExampleModel)
    if data:
        st.json(data.json())
  2. Run the streamlit server on the python script: streamlit run my_script.py

  3. You can find additional examples in the examples section below.

Examples


๐Ÿ‘‰ย  Try out and explore these examples in our playground here


The following collection of examples demonstrate how Streamlit Pydantic can be applied in more advanced scenarios. You can find additional - even more advanced - examples in the examples folder or in the playground.

Simple Form

import streamlit as st
from pydantic import BaseModel

import streamlit_pydantic as sp


class ExampleModel(BaseModel):
    some_text: str
    some_number: int
    some_boolean: bool

data = sp.pydantic_form(key="my_form", model=ExampleModel)
if data:
    st.json(data.json())

Date Validation

import streamlit as st
from pydantic import BaseModel, Field, HttpUrl
from pydantic.color import Color

import streamlit_pydantic as sp


class ExampleModel(BaseModel):
    url: HttpUrl
    color: Color
    email: str = Field(..., max_length=100, regex=r"^\S+@\S+$")


data = sp.pydantic_form(key="my_form", model=ExampleModel)
if data:
    st.json(data.json())

Dataclasses Support

import dataclasses
import json

import streamlit as st
from pydantic.json import pydantic_encoder

import streamlit_pydantic as sp


@dataclasses.dataclass
class ExampleModel:
    some_number: int
    some_boolean: bool
    some_text: str = "default input"


data = sp.pydantic_form(key="my_form", model=ExampleModel)
if data:
    st.json(json.dumps(data, default=pydantic_encoder))

Complex Nested Model

from enum import Enum
from typing import Set

import streamlit as st
from pydantic import BaseModel, Field, ValidationError, parse_obj_as

import streamlit_pydantic as sp


class OtherData(BaseModel):
    text: str
    integer: int


class SelectionValue(str, Enum):
    FOO = "foo"
    BAR = "bar"


class ExampleModel(BaseModel):
    long_text: str = Field(..., description="Unlimited text property")
    integer_in_range: int = Field(
        20,
        ge=10,
        lt=30,
        multiple_of=2,
        description="Number property with a limited range.",
    )
    single_selection: SelectionValue = Field(
        ..., description="Only select a single item from a set."
    )
    multi_selection: Set[SelectionValue] = Field(
        ..., description="Allows multiple items from a set."
    )
    single_object: OtherData = Field(
        ...,
        description="Another object embedded into this model.",
    )


data = sp.pydantic_form(key="my_form", model=ExampleModel)
if data:
    st.json(data.json())

Render Input

from pydantic import BaseModel

import streamlit_pydantic as sp


class ExampleModel(BaseModel):
    some_text: str
    some_number: int = 10  # Optional
    some_boolean: bool = True  # Option


input_data = sp.pydantic_input("model_input", ExampleModel, use_sidebar=True)

Render Output

import datetime

from pydantic import BaseModel, Field

import streamlit_pydantic as sp


class ExampleModel(BaseModel):
    text: str = Field(..., description="A text property")
    integer: int = Field(..., description="An integer property.")
    date: datetime.date = Field(..., description="A date.")


instance = ExampleModel(text="Some text", integer=40, date=datetime.date.today())
sp.pydantic_output(instance)

Custom Form

import streamlit as st
from pydantic import BaseModel

import streamlit_pydantic as sp


class ExampleModel(BaseModel):
    some_text: str
    some_number: int = 10
    some_boolean: bool = True


with st.form(key="pydantic_form"):
    sp.pydantic_input(key="my_input_model", model=ExampleModel)
    submit_button = st.form_submit_button(label="Submit")

Support & Feedback

Type Channel
๐Ÿšจย  Bug Reports
๐ŸŽย  Feature Requests
๐Ÿ‘ฉโ€๐Ÿ’ปย  Usage Questions
๐Ÿ“ขย  Announcements

Documentation

The API documentation can be found here. To generate UI elements, you can use the high-level pydantic_form method. Or the more flexible lower-level pydantic_input and pydantic_output methods. See the examples section on how to use those methods.

Contribution

Development

To build the project and run the style/linter checks, execute:

make install
make check

Run make help to see additional commands for development.


Licensed MIT. Created and maintained with โค๏ธย  by developers from Berlin.

streamlit-pydantic's People

Contributors

benediktprusas avatar hil340 avatar lukasmasuch avatar stallboy avatar szabi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

streamlit-pydantic's Issues

Expander for long Forms / inputs

Hey @LukasMasuch , @HIL340 ,

just a simple feature request:
is it somehow possible to have (for long forms) expanders as option for the input?
So one would somehow need to define the upper most level (in case of nested BaseModels) and
enable expanders between each nested model. For example here:

class Address(BaseModel):
    street: str
    city: str
    house: int


class GeneralData(BaseModel):
    email: str
    gender: bool


class ContactMethod(BaseModel):
    text: str   
   Post: List[PostalAddress]
   EmailAddress: List[GeneralData]

I would like to have an expander between Post and Email . Is that possible?

Best regards
Chris

What is the difference between `default` and `init_value`?

Describe the issue:
Hi, I noticed that there are two fields, default and init_value, that can be used in Field. May I ask what the difference is between these two fields? It seems that their effects are the same, but is the priority of init_value higher than default?
Thank you.

Technical details:

  • Host Machine OS (Windows/Linux/Mac):

Support for camelCase or CamelCase

Feature description:

Great plugin
It appears that support is only available for snake_case variables in data classes. Can you please support camelCase and CamelCase

Is this something you're interested in working on?

Yes

Double ended slider

Feature description:
Generate a double ended slider when providing a maximum and minimum argument to Field.

Streamlit provides a double ended slider when setting value to a list of integers that specify the range in st.slider(). In _render_single_number_input you only check for min_value and set value accordingly. By replacing L610 with

if "min_value" in streamlit_kwargs and "max_value" in streamlit_kwargs:
    streamlit_kwargs["value"] = [
           streamlit_kwargs["min_value"],
           streamlit_kwargs["max_value"],
    ]
elif "min_value" in streamlit_kwargs:

you would get a double ended slider. I can create a PR if you like, but I am struggling with building the project see #12.

Problem and motivation:

It is a feature of streamlit and in my work we often need to specify ranges. I think this is very common in a lot of fields.

Is this something you're interested in working on?
Yes, I already did.

Nested models with pydantic 2.0

Describe the bug:

With pydantic 2.0 (using the patched version from #35), I get an error on nested models.

class DisplaySettings(BaseModel):
    multiline: bool
    sort_on: str  # Literal['best_value', 'most_hits']


class InputSettings(BaseModel):
    autocomplete: bool


class OtherSettings(BaseModel):
    ids: list[NonNegativeInt]
    other_ids: list[NonNegativeInt]


class Settings(BaseModel):
    display: DisplaySettings
    input: InputSettings
    ltner: OtherSettings

class User(BaseModel):
    password: SecretStr
    settings: Settings

value = pydantic_form(model=User)

only renders the text_input (for password) visually, and consequently, when pressing "Submit" in the form, will rightly refuse to create a corresponding instance, as there are missing required arguments (settings).

When debugging, the problem happens in ui_rendere.py:117, when getting the _schema_references: I get a warning:

[WARNING] <streamlit.runtime.scriptrunner.script_run_context> Thread 'Thread-73': missing ScriptRunContext

and self._schema_references is set to {}.

This {} is also the reason for the missing input behaviour, as the references cannot be resolved.

See note below for a partial fix!

Expected behaviour:

Nested models working

Steps to reproduce the issue:

See snippet above.

Technical details:

  • Host Machine OS (Windows/Linux/Mac): Windows
  • Browser (Chrome/Firefox/Safari): Firefox
  • Streamlit: 1.24.1
  • Pydantic: 2.0.3

Possible Fix:

It seems that the internal schema of the model classes have changed with 2.0

In ui_renderer.py, line 118 and 1171 in the .get changing "definitions" to "$defs" seems to work in the first order:
Next to password also the settings defined in DisplaySettings and InputSettings are rendered.
BUT there is still a problem with the list fields nested in OtherSettings which needs further investigation.

I'm sorry that the PR #35 was not enough to make the lib fully pydantic 2.0 compliant.

As I said, s/"definitions"/"$defs"/ solves some of the problems, but still not all.

InputUI.render_ui silences important streamlit exceptions

Describe the bug:
My specific use case was combining sp.pydantic_form and a List data field:

from typing import List

import streamlit_pydantic as sp
from pydantic import BaseModel, Field

class ShowcaseModel(BaseModel):
    int_list: List[int] = Field(..., title="Int List title", description="Int List desc")
    str_list: List[str]

session_data = sp.pydantic_form(
    key="form",
    model=ShowcaseModel
)

This yields the following:

Note: I'm filing this as a bug since the current behavior renders a hard to debug, unexpected UI.

Expected behaviour:
I expected something similar to using sp.pydantic_input:

Additional context:
streamlit does not support buttons inside forms (see feature request in streamlit/streamlit#4892).
This is the real culprit of the half-rendered output. But it has a pretty way to inform users about what happened:

import streamlit as st

with st.form(key="key"):
    st.button("label")
    submit_button = st.form_submit_button(label="submit")

Possible Fix:
Considering the example in this issue, the rendering process stops at the first st.button found:

self._render_list_add_button(key, add_col, data_list)

Then streamlit raises a StreamlitAPIException, that is silenced within InputUI.render_ui:

try:
value = self._render_property(streamlit_app, property_key, property)
if not self._is_value_ignored(property_key, value):
self._store_value(property_key, value)
except Exception:
pass

It would be helpful to do at least one of:

  • Warn users when using sp.pydantic_form+fields that use buttons
  • Re-raise StreamlitAPIException (so streamlit properly renders it)
  • Log the exception (similarly to OutputUI.render_ui)

A similar issue can happen in other scenarios that trigger the except -> pass behavior.

I can also create a PR if you point me in the right direction.

dependant property input

Feature description:
streamlit_pydantic should have capability to handle dependant property.

Problem and motivation:
Sometimes, one property is required only when another property is True, for example:
class General(BaseModel):
legal_name: str
operating_name: Optional[str]
has_lmia_approved: bool
when_lmia_approved: Optional[date]

in streamlit_pydantic, we cannot disappear when_lmia_approved if has_lmia_approved is False.

Is this something you're interested in working on?
Yes.

Code for simple for throws PydanticImportError

Code for Simple Form in README.md cannot be run

I was starting out with streamlit-pydantic and tried to run the code for the simple form given in the README.md, but I encountered an import error while running the simple example.

2023-07-21 20:33:40.546 Uncaught app exception
Traceback (most recent call last):
  File "/Users/ayangangopadhyay/Documents/Projects/Expenditure_Dashboard/.venv/lib/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 552, in _run_script
    exec(code, module.__dict__)
  File "/Users/ayangangopadhyay/Documents/Projects/Expenditure_Dashboard/simple_form.py", line 4, in <module>
    import streamlit_pydantic as sp
  File "/Users/ayangangopadhyay/Documents/Projects/Expenditure_Dashboard/.venv/lib/python3.10/site-packages/streamlit_pydantic/__init__.py", line 9, in <module>
    from .settings import StreamlitSettings
  File "/Users/ayangangopadhyay/Documents/Projects/Expenditure_Dashboard/.venv/lib/python3.10/site-packages/streamlit_pydantic/settings.py", line 4, in <module>
    from pydantic import BaseSettings
  File "/Users/ayangangopadhyay/Documents/Projects/Expenditure_Dashboard/.venv/lib/python3.10/site-packages/pydantic/__init__.py", line 207, in __getattr__
    return _getattr_migration(attr_name)
  File "/Users/ayangangopadhyay/Documents/Projects/Expenditure_Dashboard/.venv/lib/python3.10/site-packages/pydantic/_migration.py", line 288, in wrapper
    raise PydanticImportError(
pydantic.errors.PydanticImportError: `BaseSettings` has been moved to the `pydantic-settings` package. See https://docs.pydantic.dev/2.0.3/migration/#basesettings-has-moved-to-pydantic-settings for more details.

For further information visit https://errors.pydantic.dev/2.0.3/u/import-error

The code I am trying to run is exactly the one given for the simple form -

import streamlit as st
from pydantic import BaseModel
import streamlit_pydantic as sp

class ExampleModel(BaseModel):
    some_text: str
    some_number: int
    some_boolean: bool

data = sp.pydantic_form(key="my_form", model=ExampleModel)
if data:
    st.json(data.json())

Expected behaviour:

Rendering a simple form with streamlit-pydantic.

Steps to reproduce the issue:

  1. Create a .venv
  2. Install required dependencies
  3. Create the simple_form.py file using the above code or copying it from the README.md
  4. streamlit run simple_form.py

-->

Technical details:

  • Host Machine OS (Windows/Linux/Mac): Mac
  • Browser (Chrome/Firefox/Safari): Arc/Mozilla
  • Python Version: 3.10.8
  • streamlit-pydantic Version: 0.6.0
  • streamlit: 1.24.1

Please let me know if any further details are required, and I will be happy to provide them. Thanks!

ignore_empty_values doesn't work for list types

Describe the bug:
When setting ignore_empty_values=True, I would expect empty lists to not be returned by pydantic_input. Yet they are.

Possible Fix:
Update _is_value_ignored in ui_renderer.py to check type(value) == list as follows:

return (
            self._ignore_empty_values
            and (
                type(value) == int or type(value) == float or isinstance(value, str) or type(value) == list
            )  # only for int, float or str
            and not value
            and self._get_value(property_key) is None
        )

I've tested this and it works.

Displaying Input Sections in Columns

Feature description:
As far as I understand at the moment User Input will all be displayed in one colum. As seen here
grafik
But instead i would like to display the interactive fields in multile colums, As seen here:
grafik

Maybe one could specify the number of input columns as name-value pair:

input_data = sp.pydantic_input(
    "model_input", model=ExampleModel, width=2
)

Additionaly if the width value equals None, the Number of Collums could be automaticly determined to approximate for e.g. a 3 by 4 aspect ratio. If the window size is to narrow streamlit rearranges the elements anyway.

Problem and motivation:
The motivation is clearly to make apps with a lot of user input more organised and utilize more of wide screen displays.
This is espacially sensible, since streamlit-pydantic is a usefull tool espacially in applications with a lot of user input, to make code more organised and modular.

Is this something you're interested in working on?
Yes, although I am totally inexperienced

Base setting is changed to pydantic_settings

Describe the bug:

Base setting is changed to pydantic_settings instead of pydantic.

Expected behaviour:

Base setting is changed to pydantic_settings to new module

Steps to reproduce the issue:

Go to file

Technical details:

  • Host Machine OS (Windows/Linux/Mac):
  • Browser (Chrome/Firefox/Safari):

Possible Fix:

Additional context:

Lists(except files list) do not work in sidebar forms

Description:

lists of integers or strings (or in my assumption any other primitive type) as datatype does not work when using in sidebar form.
The above does not occur and we get the clear and add item buttons but they disappear when used insidebar forms

Expected Behaviour:

this should be consistent across all forms (for my use-case at least sidebar-form)

Steps to reproduce:

class IDsModel(BaseModel):
    ids: List[str] =  Field( [], max_items=8, description="Enter ids")

with st.sidebar.form(key="dummy_form"):
    dummy_session_data = sp.pydantic_input(key="dummy_model", model=IDsModel)

P.S. love the pydantic <-> streamlit integration <3

Nested `pydantic_form` not working, just clears page

Describe the bug:

When I try to have nested pydantic_forms, the page just gets cleared out.

Expected behaviour:

I expect the below code snippet to not wipe the screen after the second submit button is pressed.

Steps to reproduce the issue:

import streamlit as st
import streamlit_pydantic as sp
from pydantic import BaseModel, Field

class MinCount(BaseModel):
    min_count: int = Field(default=4, gt=0)

st.title("Test")
input_1 = sp.pydantic_form(key="input-1", model=MinCount)
if input_1:
    input_2 = sp.pydantic_form(key="input-2", model=MinCount)
    if input_2:
        st.write(f"{input_1.min_count=}, {input_2.min_count=}.")

Technical details:

  • Host Machine OS (Windows/Linux/Mac): macOS Ventura version 14.5.2, arm64
  • Browser (Chrome/Firefox/Safari): Chrome

Here are my requirements with Python 3.11:

pydantic                  2.5.2
pydantic_core             2.14.5
pydantic-settings         2.1.0
streamlit                 1.28.2
streamlit-pydantic        0.7.1

I am installing https://github.com/LukasMasuch/streamlit-pydantic/tree/390a45aba7bf8caccc297c335715cc141db490af directly from GitHub

Possible Fix:

Additional context:

Import error due to Pydantic v2.0

Currently setup.py requires pydantic => 1.9, Pydantic 2.0 just released today and it is causing some import errors.

Technical details:

  • Host Machine OS (Windows/Linux/Mac): Windows

Support for custom Pydantic fields

Thanks for making this repo @LukasMasuch!
I would love to use your library in my repo but I would need to make it work with custom Pydantic fields like your FileContent class. How would you integrate that feature? I see that the elements are rendered by the various methods like def _render_single_file_input of InputUI. I think it would be really nice if it was possible to add custom renderers for specific classes. Maybe kept in a dictionary. Then every user can add their elements if desired and at rendering the dictionary is scanned first for a matching entry. What do you think?

Add a single input of type radio.

Feature description:
Hello. In my scenario, I want to show a Radio UI for user. It seems that is not currently supported.

I think there will be two ways to add radio type, one is that pass a "ui_type" into "Field", another is that provider a new type "RadioType" like "FileContent". If you have a better way, please let me know, thank you very much~

Problem and motivation:
Such as:
image

Is this something you're interested in working on?

yes

How to populate a form with a model instance?

Describe the issue:
How can I populate a form with an instance of a model that e.g. is loaded from a database? I was hoping for sth. like this to work:

model = ExampleModel(long_text="This is a long text property.", integer_in_range=24)

data = sp.pydantic_form(key="my_form", model=model)

Brilliant project though, exactly what I was looking for!

Building the project after clean fork fails with mypy error

Describe the bug:
When I try to build the project using the instructions under the section Development in README.md, one of the code checks fails.

I forked your latest main branch and tried to run the instructions for development. After running PIPENV_IGNORE_VIRTUALENVS=1 python build.py --make --check mypy reports an error.

src/streamlit_pydantic/ui_renderer.py:1070: error: Argument 1 to "join" of "str" has incompatible type "Tuple[Union[int, str], ...]"; expected "Iterable[str]"

Expected behaviour:

I would have expected all checks to pass on the master branch.

Steps to reproduce the issue:
Clone the repo and checkout master (1afd4e3)

pip install universal-build
python build.py --make --check

In my case I used PIPENV_IGNORE_VIRTUALENVS=1 to ignore my current virtual environment.

Technical details:

  • Host Machine Mac OS
  • Python 3.9.5

Possible Fix:

Have a look at the specified line in the mypy output.

Additional context:
When running pip install universal-build
python build.py --make --check for the first time it complained about missing wheel and twine.

Forms for list-valued models do not work

This bug regarding lists-values was first described in a comment to #36. #36 in the strict sense is fixed by merged-not-yet-released PR #37. I open this issue to track the list-valued problem separately, which does not seem to be related to pydantic 2.

Describe the bug:

List valued models do not work. There is code in streamlit-pydantic for handling list-valued models that suggest that it might have worked earlier, but at least with current versions of streamlit, list-valued models do not render as forms.

List-Editing is solved in streamlit-pydantic among others by adding a button: self._render_list_add_button(key, add_col, data_list) (ui_renderer.py:1000), but that tries to add a streamlit.button(...) to the interface. However, adding a regular button within a form is disallowed by streamlit button.py:407-411 raising an exception. Only form-submit buttons are currently allowed in Streamlit within forms. (The exception raising was part of Streamlit from the very beginning of adding the "form" feature in April 2021, so it's not clear how list valued editing was supposed to work in streamlit-pydantic to begin with)

The exception then seems to be silently caught and ignored by streamlit-pydantic, so that the form does not render, correctly, but also no exception is displayed within the streamlit app.

Expected behaviour:

List valued models should be also rendered and editing should be possible with streamlit-pydantic.

Steps to reproduce the issue:

You can use the example used in #36 on a codebase which has #37 merged to reproduce. OtherSettings has : list[NonNegativeInt] values.

Technical details:

  • Host Machine OS (Windows/Linux/Mac): Windows
  • Browser (Chrome/Firefox/Safari): Firefox

Notes:

Given that the raising of the specific exception in Streamlit is quite intentional and seems to be a core design decision, an alternative mode to edit lists has to be found, if possible at all.

After a quick browse through streamlit elements it can maybe solved by a "data editor" element, though the result would likely be unsightly and cumbersome. Similarly cumbersome would be using a "text input" with some convention for splitting the values. Neither seems to be a particularly good solution, the solution space needs to be explored further.

add 'disabled: bool = False' kwarg to sp.pydantic_form

Feature description:
Please expose a 'disabled: bool = False' kwarg in sp.pydantic_form(). It should either disable all input fields or just disable the submit, both work.
I prefer to just disable the submit button, but thats a UI question.

Problem and motivation:
External state that prohibits the form to be send off. [Long Running API call following the Submit, Selection of another filed must happen first, ....]

Is this something you're interested in working on?
No

Handle Collection Type fields

Feature description:
Correctly handle fields such as List[str]

Curently when a field is of a collection type such as dict, list, Mapping, Sequence etc. the behaviour is broken.
For the model

class ExampleModel(BaseModel):
        text: str
        many_texts: Sequence[str]

the output is broken
image
and pressing the submit button results in the following error
Whoops! There were some problems with your input: many_texts: field required

Problem and motivation:

I have forms where some of the inputs are an arbitrary number of strings. Up until now I have solved this with a text_area widget, and prompt the user to separate their inputs with commas. Then with a custom validator the strings can be put back into a list. While this kinda works, it is a very hacky solution, it prevents me from using this package without breaking up my model

Is this something you're interested in working on?

Currently I don't have the capacity but it is something that am willing to look into in the near future (in a couple of months)

Complex Nested Model Is not working

Describe the bug:

When I try to replicate the complex Nested model, it raises a warning The type of the following property is currently not supported

Basic Demo does not appear up to date

Describe the bug:

Hi all, love the idea of the package.

I am trying to run the basic example in the readme:

import streamlit as st
from pydantic import BaseModel

import streamlit_pydantic as sp


class ExampleModel(BaseModel):
    some_text: str
    some_number: int
    some_boolean: bool


data = sp.pydantic_form(key="my_form", model=ExampleModel)
if data:
    st.json(data.json())

But I get the error:

PydanticImportError: BaseSettings has been moved to the pydantic-settings package. See https://docs.pydantic.dev/2.5/migration/#basesettings-has-moved-to-pydantic-settings for more details. For further information visit https://errors.pydantic.dev/2.5/u/import-error

I initially thought this might be duplicate of #52 or #38, but I the settings aren't directly imported in the code. Maybe it's easiest to update the code in the readme so the newbie's like me understand how to use this module :)

Technical details:

I am using python 3.11.7 and these package versions:

pydantic 2.5.3
pydantic_core 2.14.6
pydantic-settings 2.1.0
streamlit-pydantic 0.6.0

Optional[str] fields fail to render

Describe the bug:

When attempting to run the provided test for optional fields:
https://github.com/LukasMasuch/streamlit-pydantic/blob/390a45aba7bf8caccc297c335715cc141db490af/examples/optional_fields.py

The library is not able to render anything with strings it seems like. This is also true for more complex classes. The library is able to render the text if the Optional typing is removed.

Expected behaviour:

The field should be rendered as any other string field.

Steps to reproduce the issue:

  1. Checkout the most recent commit 390a45a
  2. Install
  3. Run the optional_fields.py example provided in the repository

Technical details:

  • Windows
  • Chrome

Download button

Feature description:

I would like to have the ability to include a download button as output.

Problem and motivation:

My script receives some input, processes it and generates a downloadable zip file containing some documents, I would like to allow the user to download it in an easy way.

Is this something you're interested in working on?

Yes: I work in Python, but I am new to both streamlit and pydantic, so it may take some time.

`Streamlit Settings` playground app is currently broken

Describe the bug:

The Streamlit Settings playground is currently failing:

image

Note: A similar error also occurs when running the playground app locally.

Expected behaviour:

Not sure!

Steps to reproduce the issue:

  1. Go to the deployed playground
  2. Click on the 'Streamlit Settings' demo
  3. See error

Technical details:

  • Host Machine OS (Windows):
  • Browser (Firefox):

Possible Fix:

Recent changes to streamlit-pydantic or streamlit or pydantic may have broken this functionality.

Additional context:

Request: cutting new release

Looks like #35 fixes a pydantic-settings import issue.

Any chance we can cut a new release to make this change accessible?

This is a duplicate of #41, #43

Requirements.txt

Thank you so much for the fantastic Streamlit plugin!

I'm currently facing some challenges in getting the examples to run smoothly. Could someone please share a requirements.txt file that is compatible with the provided examples?

Many thanks in advance!

Return pydantic object from function

Thanks for making this repo @LukasMasuch! Excited to start playing with it. Would you be open to a PR to modify the API so that sd.pydantic_input() returns the instantiated pydantic object, or None if the inputs are invalid? If so I can play around with that

Support for Union class.

Cool project @LukasMasuch, thank you!

Feature description:

I'm missing support for Unions. Ver simple example can be:

class PostalAddress(BaseClass):
    street: str
    city: str
    house: int
    
class EmailAddress(BaseClass):
    email: str
    send_news: bool
    
class ContactMethod(BaseClass):
    contact: Union[PostalAddress, EmailAddress]
    ... other fields
    
    
# rendring form for ClassMethod

So far I'm doing it with radio button, depending on its output the right option is rendered.

I'm not sure if there is more elegant solution, but let me know if you have ideas so I could help with implementing

Optional field are set to value if input is not passed in json output

Optional field are set to value if input is not passed in json output.

Describe the bug:

This output of this code if opt_int is not set is the one reported in the picture

class ModelTest(BaseModel):
    name: str = Field(title='Name')
    opt_int: Optional[int] = Field(title='Optional int')

data = sp.pydantic_form(model=ModelTest, key="Data entry", group_optional_fields='expander')
st.text(data)

image

while the
Expected behaviour:
is a json containing only the user input
{name='a'}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.