How to bind value from pydantic.BaseModel to a ui.range() #4046
-
QuestionI have a pydantic.BaseModel in which I define a min and max attribute. The min/max values is assigned to the ui.range at startup via model_dump(). That works. from nicegui import ui
from pydantic import BaseModel
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,
value=j.value.model_dump()
).props('label-always color="red"').bind_value_from(j, "value")
ui.button(on_click=change_value_model)
ui.run() The binding works when the value is a dict (with "min" and "max "as key): than I can do |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @TeeFiX42, Because you want user input to propagate into the model and vice versa, you need two-way binding with 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())
ui.button(on_click=change_value_model) |
Beta Was this translation helpful? Give feedback.
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 withbind_value_from()
. And you need to define the conversion between aValue
instance and a dictionary with "min" and "max". This can be done via theforward
andbackward
parameters: