Python Flask Wtform Selectfield With Enum Values 'not A Valid Choice' Upon Validation
My Python Flask app is using WTForms with built in python Enum support. I'm attempting to submit a form (POST) where a SelectField is populated by all values of a Enum. When I hit
Solution 1:
Is there a way to coerce WTForms
The argument you're looking for is actually called coerce
, and it accepts a callable that converts the string representation of the field to the choice's value.
- The choice value should be an
Enum
instance - The field value should be
str(Enum.value)
- The field text should be
Enum.name
To accomplish this, I've extended Enum
with some WTForms
helpers:
classFormEnum(Enum):
@classmethoddefchoices(cls):
return [(choice, choice.name) for choice in cls]
@classmethoddefcoerce(cls, item):
return cls(int(item)) ifnotisinstance(item, cls) else item
def__str__(self):
returnstr(self.value)
You can then edit a FormEnum
derived value using a SelectField
:
role = SelectField(
"Role",
choices = UserRole.choices(),
coerce = UserRole.coerce)
Post a Comment for "Python Flask Wtform Selectfield With Enum Values 'not A Valid Choice' Upon Validation"