WTForms: How to select options in SelectMultipleField?

后端 未结 5 1397
抹茶落季
抹茶落季 2020-12-24 07:54

Choices can be set using form.myfield.choices=[(\"1\",\"Choice1\"), (\"2\",\"Choice2\")]

What is the way to set the selected option?

5条回答
  •  生来不讨喜
    2020-12-24 08:34

    None of these answers worked for me (WTForms 2.2); all of them led to the same issue. When I submitted data via a POST request, the values I set as defaults (whether by .default, .data, .process_data(), or .process()) would be returned to my controller regardless of edits I made to the values in the form in the browser.

    To resolve this, I passed the request type back to my controller and if it was a POST request, I skipped past the part where I set the default values.

    form = controller.getForm(request= request.method)
    

    and in the controller where I handled the submission,

    getForm(request="")
    # ...
    if request != "POST":
        # Set the default values for the form
    else:
        # Go straight to validating the form data 
    

提交回复
热议问题