John
John

Reputation: 117

Python: SelectField "Not a valid choice"

form.py

class Confirm(CSRFForm):
    monitor_updates = SelectField(
        lazy_gettext("Monitor updates of an app"),
        validators=[validators.Optional()], choices=[], coerce=int
    )

view.py

def upload_confirm():
    form = Confirm()

    if form.validate_on_submit:
        if form.monitor_updates.data == 0:
            current_workflow.installation_source.monitor_updates_id = None
            db.session.commit()
        else:
            current_workflow.installation_source.monitor_updates_id = form.monitor_updates.data
            db.session.commit()

    choices = [(app[1][0], app[1][1]) for app in list_choices]
    form.monitor_updates.choices =[(0, "Nothing matches")]
    form.monitor_updates.choices += choices

models.py

class InstallationSource(db.Model):

    monitor_updates_id = db.Column(db.Integer, db.ForeignKey('updates_software.id'))

When filling out the form and selecting "Nothing matches" in the dropdown with a value of 0, I get an error.

screenshot

If you select a different value, the save is correct. I can only use the number 0, because all other numbers can be occupied

Upvotes: 4

Views: 1790

Answers (1)

Mark
Mark

Reputation: 194

You need the logic for choices

    choices = [(app[1][0], app[1][1]) for app in list_choices]
    form.monitor_updates.choices =[(0, "Nothing matches")]
    form.monitor_updates.choices += choices

to come before the form.validate_on_submit() method:

def upload_confirm():
    form = Confirm()

    choices = [(app[1][0], app[1][1]) for app in list_choices]
    form.monitor_updates.choices =[(0, "Nothing matches")]
    form.monitor_updates.choices += choices

    if form.validate_on_submit():
        if form.monitor_updates.data == 0:
            current_workflow.installation_source.monitor_updates_id = None
            db.session.commit()
        else:
            current_workflow.installation_source.monitor_updates_id = form.monitor_updates.data
            db.session.commit()

Upvotes: 3

Related Questions