Skip to content

How to bind value from pydantic.BaseModel to a ui.range() #4046

Closed Answered by falkoschindler
TeeFiX42 asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @TeeFiX42,

Because you want user input to propagate into the model and vice versa, you need two-way binding with bind_value() rather than one-way binding with bind_value_from(). And you need to define the conversion between a Value instance and a dictionary with "min" and "max". This can be done via the forward and backward parameters:

class Value(BaseModel):
    min: float = 5
    max: float = 13

class Jos(BaseModel):
    value: Value = Value(min=3, max=8)

def change_value_model():
    j.value = Value(min=5, max=27)

j = Jos()

ui.label()
ui.range(min=2, max=50, step=1).props('label-always') \
    .bind_value(j, "value", forward=lambda v: Value(**v), backward=lambda v: v.model_dump())

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@TeeFiX42
Comment options

Answer selected by TeeFiX42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants