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
Enuminstance - 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:
class FormEnum(Enum):
@classmethod
def choices(cls):
return [(choice, choice.name) for choice in cls]
@classmethod
def coerce(cls, item):
return cls(int(item)) if not isinstance(item, cls) else item
def __str__(self):
return str(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"