Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixed issue on multi select field while selecting single item #159

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions src/python-fastui/fastui/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ def __class_getitem__(cls, model: _t.Type[FormModel]) -> fastapi_params.Depends:
def fastui_form(model: _t.Type[FormModel]) -> fastapi_params.Depends:
async def run_fastui_form(request: fastapi.Request):
async with request.form() as form_data:
model_data = unflatten(form_data)

model_data = unflatten(model, form_data)
try:
return model.model_validate(model_data)
except pydantic.ValidationError as e:
Expand Down Expand Up @@ -173,7 +172,7 @@ class SelectSearchResponse(pydantic.BaseModel):
NestedDict: _te.TypeAlias = 'dict[str | int, NestedDict | str | list[str] | ds.UploadFile | list[ds.UploadFile]]'


def unflatten(form_data: ds.FormData) -> NestedDict:
def unflatten(model: _t.Type[FormModel], form_data: ds.FormData) -> NestedDict:
"""
Unflatten a `FormData` dict into a nested dict.

Expand All @@ -194,10 +193,10 @@ def unflatten(form_data: ds.FormData) -> NestedDict:
d[part] = {}
d = d[part]

if len(values) == 1:
d[last_key] = values[0]
else:
if (last_key in model.model_fields and _t.get_origin(model.model_fields[last_key].annotation) is list) or len(values) > 1:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this isn't going to work for lots of other types e.g. tuple, set, frozenset.

Instead of introspecting the python type, I'd rather we iterated over the JSON Schema and worked out which fields should take multiple values that way.

With that we can also:

  • move the logic out of unflatten thus separating concerns
  • cache the result per model
  • have a more general solution as JSON Schema already simplifies many types into an array schema

Since we already have logic to flatten JSON Schema, we might be able to use that and therefore pass a simple dict[key, bool] to this method.

d[last_key] = values
else:
d[last_key] = values[0]

# this logic takes care of converting `dict[int, str]` to `list[str]`
# we recursively process each dict in `result_dict` and convert it to a list if all keys are ints
Expand Down
Loading