Skip to content

field.widget.format_value(cleaned_value) changes variable types when using Django forms #617

@Tubo

Description

@Tubo

If I have a form class like this:

class LeaveForm(forms.ModelForm):
    class Meta:
        model = Leave
        fields = ["date", "type", "portion", "comment"]

where "type" and "portion" are ChoiceField.

I have a Unicorn view like this:

class LeaveFormView(UnicornView):
    form_class = LeaveForm
    date: date = None
    type: str = "" 
    portion: str = ""
    comment: str = ""

If I select an option with this template:

        <select id="inputState"
                u:model="portion">
            <option value="ALL">ALL</option>
		</select>

I expect portion to be "ALL". However, I get ["ALL"] instead. This causes validation error.

After some debugging, I discovered that this line in unicorn_view.py line 468 has this call:

value = field.widget.format_value(cleaned_value)

which in turn calls ChoiceWidget.format_value which returns a list. I presume this gets propagated to the front-end and returns as a list.

I'm not sure of how Unicorn works, but I presume potential solution to this would include:

  1. Special case treatment for ChoiceField and TypedChoiceField. Both of the above uses Select widget which inherits from ChoiceWidget. You could make a special conditional for these two fields to coerce list into a basic type.
  2. Alternatively, ChoiceField has a allow_multiple_selected attribute. You could use that to decide whether to keep list or not.

Thanks again for this amazing project.

-T

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions