okoboko
okoboko

Reputation: 4482

Python - WTForms Coerce to Object

I'm using a SelectMultipleField in a WTForm class that gets values from MongoDB.The input needs to be coerced to handle these MongoDB object IDs or I get this error:

Invalid choice(s): one or more data inputs could not be coerced

I have tried the following.

groups = SelectMultipleField("Groups: ", coerce=object)

but it doesn't doesn't work.

Here's what the HTML looks like (notice the object IDs used for value):

<select class="form-control" id="groups" multiple name="groups">
    <option value="53921416b45ba747082829f1">My Group</option>
    <option value="53921c1402b8754f85446e5a">ttt</option>
    <option value="53921cf602b8755019a9562e">Developers</option>
    <option value="53921de202b875518e449bad">sadf</option>
    <option value="53921fa902b87553366482cc">asdf</option>
</select>

What is the correct way to coerce the value (to handle object IDs)?

Upvotes: 1

Views: 1623

Answers (1)

okoboko
okoboko

Reputation: 4482

It turns out you just need to use ObjectID() from MongoDB. First, import ObjectID

from bson import ObjectID

Then modify your coerce parameter to

coerce=ObjectId

Upvotes: 2

Related Questions