Setting a default on a select removes the settings

2019-05-24 04:03发布

问题:

This code works fine separately. What I mean is when I set the default tag and call process() all the other data that should populate the form have been removed. In this case the default is ok, but the other fields are empty.

form = ReviewForm(**populate_form)
form.tags.default = '1'
form.process()

So, it seems like process cleans the **populate_form values out. I need to populate all fields and then set the default for the select.

回答1:

From the WTForms Documentation:

Since BaseForm does not take its data at instantiation, you must call this to provide form data to the enclosed fields. Accessing the field’s data before calling process is not recommended.

But the Form subclass allows you to pass in objects as kwargs, which you are doing here. However, looking at the source, it looks like what is happening here is that __init__ is calling process to process the fields, so I think there is some overriding going on.

In any case, I think what is missing here is that the default value should be defined upon definition, not after instantiation. Look at the construction as well as this answer, and I think that will clear things up.