Flask Admin Display Enum Value Instead Of Name
I have a model which uses an enum to define an access level as follows: class DevelModelView(ModelView): edit_modal = True def is_accessible(self): return current_
Solution 1:
If you have several enum
types to display, rather than creating individual column_formatters
you can update the column_type_formatters that Flask-Admin uses.
Example
from flask_admin.model import typefmt
classAccessLevel(Enum):
DEVEL = 'Developer'
ADMIN = 'Administrator'
STAFF = 'Staff Member'# ...
MY_DEFAULT_FORMATTERS = dict(typefmt.BASE_FORMATTERS)
MY_DEFAULT_FORMATTERS.update({
AccessLevel: lambda view, access_level_enum: access_level_enum.value # could use a function here
})
classDevelModelView(ModelView):
column_type_formatters = MY_DEFAULT_FORMATTERS
# ...
Also consider setting up the AccessLevel choices as described in this SO answer. It means you don't have to repeat the enum name/values in your model view definition. Note the __str__
and __html__
methods in the AccessLevel
class.
Example
from flask_admin.model import typefmt
from wtforms import SelectField
classAccessLevel(Enum):
DEVEL = 'Developer'
ADMIN = 'Administrator'
STAFF = 'Staff Member'def__str__(self):
return self.name # value stringdef__html__(self):
return self.value # option labelsdefenum_field_options(enum):
"""Produce WTForm Field instance configuration options for an Enum
Returns a dictionary with 'choices' and 'coerce' keys, use this as
**enum_fields_options(EnumClass) when constructing a field:
enum_selection = SelectField("Enum Selection", **enum_field_options(EnumClass))
Labels are produced from enum_instance.__html__() or
str(eum_instance), value strings with str(enum_instance).
"""assertnot {'__str__', '__html__'}.isdisjoint(vars(enum)), (
"The {!r} enum class does not implement a __str__ or __html__ method")
defcoerce(name):
ifisinstance(name, enum):
# already coerced to instance of this enumreturn name
try:
return enum[name]
except KeyError:
raise ValueError(name)
returndict(choices=[(v, v) for v in enum], coerce=coerce)
classDevelModelView(ModelView):
column_type_formatters = MY_DEFAULT_FORMATTERS
# ...
form_overrides = {
'access': SelectField,
}
form_args = {
'access': enum_field_options(AccessLevel),
}
# ...
Solution 2:
You need column_formatters functionality to display proper values in the table. Formatter function is defined like this:
defaccess_level_formatter(view, context, model, name):
db_value = getattr(model, name)
enum_value = getattr(AccessLevel, db_value)
return enum_value.value
And you need to specify this formatter in the view class that it is used for the access
column:
classDevelStaffModelView(DevelModelView):
column_formatters = {
'access': access_level_formatter,
}
Post a Comment for "Flask Admin Display Enum Value Instead Of Name"