Skip to content

Instantly share code, notes, and snippets.

@WorldException
Created September 30, 2021 05:52
Show Gist options
  • Save WorldException/c7283f7546fb54ec7df5c7708bfc47c8 to your computer and use it in GitHub Desktop.
Save WorldException/c7283f7546fb54ec7df5c7708bfc47c8 to your computer and use it in GitHub Desktop.
SelectFieldDynamic use function for choices
class SelectFieldDynamic(SelectField):
# use function in choices
def __init__(self, label=None, validators=None, coerce=str, choices=None, validate_choice=True, **kwargs):
super(SelectFieldDynamic, self).__init__(label, validators, **kwargs)
self.coerce = coerce
self.choices = choices
self.validate_choice = validate_choice
def iter_choices(self):
if not self.choices:
choices = []
elif callable(self.choices):
choices = self.choices()
elif isinstance(self.choices[0], (list, tuple)):
choices = self.choices
else:
choices = zip(self.choices, self.choices)
for value, label in choices:
yield (value, label, self.coerce(value) == self.data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment