[Python] wtforms: optional FieldList of IntegerField?

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I need an optional list of int's in a WTForms-validated Rest API.

    Right now this is the relevant part of my form:

    from wtforms import IntegerField, FileField, StringField, FieldList
    from wtforms.validators import DataRequired, Optional, UUID

    class PublishForm(FlaskForm):
    # This validates, but the patch_bases list comes up empty.
    # patch_bases = FieldList(IntegerField("pb", validators=[Required()]), min_entries=0, max_entries=5, validators=[Optional()])
    # This too.
    patch_bases = FieldList(IntegerField(), min_entries=0, max_entries=5, validators=[Optional()])


    Here's the call to validate/parse:

    form = PublishForm()
    if not form.validate_on_submit():
    return form_error_response(form.errors)


    And here's (part of) a test curl I'm using to hit the API:

    curl \
    -v \
    -X POST \
    -H "Authorization: Bearer $(set -eu; cat token)" \
    --form 'patch_bases=[2, 4]' \
    http://hostname:8080/api/v3/publish


    I'm using --form because I need to upload a file as well (not shown here).

    I'm consistently getting back a "successfully validated" empty list even when I pass a nonempty list of int's via curl, which is not what I want.

    What I want, ideally, is a None for no patch_bases field specified at all, an empty list for patch_bases=[], or a nonempty list for 1 to 5 int's in patch_bases - all in form.patch_bases.data.

    I've Googled about this extensively on more than one occasion, but I'm not seeing a way of doing what I want.

    I'm using:

    WTForms 2.0.2
    Python 3.10.12


    I know, the WTForms version is ancient, but I'm stuck with it for now unless there's a pretty compelling reason to upgrade.

    If there's a fine manual to read, feel free to point me at it? I dug around in the WTForms 2.3.x doc on Fields (among many other Google hits), but didn't see what I need.

    Thanks!

    Continue reading...

Compartilhe esta Página